﻿using System;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
using System.IO;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Web.UI;
using System.Deployment.Application;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.OleDb;
//
using HRM.Properties;
using UpdateAuto;
using HRM.Utilities;
using HRM;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using HRM.Common;
using System.Runtime.CompilerServices;
using HRM.BusinessLogic;
using DetailInfo = HRM.BusinessLogic.BhDetailInfo;

namespace HRM
{
    public partial class frmMain : Form
    {
        frmProgressbar fProgress;
        HeaderClient _wcfHeader;
        //DetailClient _wcfDetail;
        DetailInfo _DetailInfo;
        GradeClient _wcfGrade;
        PositionClient _wcfPosition;
        EmployeeClient _wcfEmployee;
        EmployeeInfo _EmployeeInfo;
        DepartmentClient _wcfDepartment;
        PositionDetailClient _wcfPD;
        PositionDetailInfo _PDInfo;
        public bool isFirstLoad;

        Dictionary<string, string> dicInitFormat = null;
        public frmMain()
        {
            InitializeComponent();
            //
            Init_Control();
            //
            Program.frmMain = this;
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized; //Full màn hình
        }

        //Lưu định dạng format status strip
        private void StatusStrip_Init()
        {
            dicInitFormat = new Dictionary<string, string>();
            foreach (ToolStripItem ctr in statusStrip.Items)
            {
                if (ctr.Text.IndexOfAny(new char[] { '{', '}' }) > 0 && !dicInitFormat.ContainsKey(ctr.Name))
                    dicInitFormat.Add(ctr.Name, ctr.Text);
            }
        }

        private void StatusStrip_SetText(ToolStripItem tsi, string sText)
        {
            tsi.Text = dicInitFormat.ContainsKey(tsi.Name) ? String.Format(dicInitFormat[tsi.Name], sText) : sText;
        }

        private void Notifier_Init()
        {
            Program.taskbarNotifier = new TaskbarNotifier();
            Program.taskbarNotifier.SetBackgroundBitmap(HRM.Properties.Resources.skin, Color.FromArgb(0, 172, 238));
            Program.taskbarNotifier.TitleRectangle = new Rectangle(8, 9, 70, 25);
            Program.taskbarNotifier.ContentRectangle = new Rectangle(8, 41, 133, 68);
            Program.taskbarNotifier.CloseClickable = true;
            Program.taskbarNotifier.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            Program.taskbarNotifier.TitleClickable = false;
            Program.taskbarNotifier.ContentClickable = false;
            Program.taskbarNotifier.EnableSelectionRectangle = false;
            Program.taskbarNotifier.KeepVisibleOnMousOver = true;
            Program.taskbarNotifier.ReShowOnMouseOver = false;
        }

        //Khởi tạo cho các control
        private void Init_Control()
        {
            Notifier_Init();
            StatusStrip_Init();
            //
            FormGlobals.ToolStrip_SetViewOnly(false, mnuInterestRate, mnuTax, mnuEmployeeShift, mnuLoadCheckTime, mnuViewAttend, mnuLaterInsurance, mnuFundSalary, mnuEvaluation, mnuImportEmployee, mnuDept);
            //
            switch (Program.strLanguage)
            {
                case "vi":
                    cboLanguage.SelectedIndex = 0;
                    break;
                case "en":
                    cboLanguage.SelectedIndex = 1;
                    break;
            }
            helpProvider1.HelpNamespace = Application.StartupPath + "\\huongdan_HRM goc.pdf";

            //Show Version
            tlbVersion.Text = UpdateUI.GetString(tlbVersion.Tag.ToString()) + ": " + Program.Version.ToString().Substring(0, 1) + "." + Program.Version.ToString().Substring(1, 1) + "." + Program.Version.ToString().Substring(2, 1) + "." + Program.Version.ToString().Substring(3);
            tlbServerAdd.Text = String.Format(tlbServerAdd.Text, Properties.Settings.Default.ServiceAddress);
            tblTime.Text = DateTime.Now.ToString(Globals.CS_DISPLAY_TIMEDATE_FORMAT);
            //
            _wcfHeader = Service.Header();

            //Gán sự kiện click vào các menu
            System.Windows.Forms.ToolStripItemClickedEventHandler itemClick;
            ToolStripMenuItem mnuRoot;

            for (int i = 0; i < mnuMain.Items.Count; i++)
            {
                if (mnuMain.Items[i] is ToolStripMenuItem)
                {
                    mnuRoot = mnuMain.Items[i] as ToolStripMenuItem;
                    itemClick = null;
                    if (mnuRoot.DropDownItems.Count == 0
                        //|| mnuRoot.Name == emnuOutbound.Name 
                        || mnuRoot.Name == mnuReport.Name
                        || mnuRoot.Name == mnuList.Name

                        )
                    {
                        switch (mnuRoot.Name)
                        {
                            case "mnuReport":
                                modReport.Menu_Init(mnuRoot);
                                break;
                            case "mnuList":
                                modList.Menu_Init(mnuRoot);
                                break;
                        }
                        continue;
                    }
                    switch (mnuRoot.Name)
                    {
                        case "mnuReport":
                            itemClick = new System.Windows.Forms.ToolStripItemClickedEventHandler(modReport.Menu_DropDownItemClicked);
                            break;
                        case "mnuList":
                            itemClick = new System.Windows.Forms.ToolStripItemClickedEventHandler(modList.Menu_DropDownItemClicked);
                            break;
                    }
                    if (itemClick != null)
                    {
                        Menu_AutoInit(mnuRoot, itemClick);
                    }
                }
            }
        }

        private void Menu_AutoInit(ToolStripMenuItem mnuRoot, ToolStripItemClickedEventHandler itemClick)
        {
            if (mnuRoot.DropDownItems.Count > 0)
                mnuRoot.DropDownItemClicked += itemClick;
            //
            int iIndex = 0;
            foreach (ToolStripItem itmChild in mnuRoot.DropDownItems)
            {
                if (itmChild is ToolStripMenuItem)
                {
                    Menu_AutoInit((ToolStripMenuItem)itmChild, itemClick);
                    iIndex += 1;
                    if (!itmChild.Text.StartsWith("&"))
                    {
                        itmChild.Text = String.Format("&{0}. ", iIndex.ToString("X")) + itmChild.Text;
                    }
                }
            }
        }

        //Hiện form chờ login
        private void OpenSplash()
        {
            fProgress = new frmProgressbar();
            fProgress.Show();
            fProgress.Refresh();
            Application.DoEvents();
            LoadCheckTime();
            fProgress.Close();
        }

        private void MessageBoard(int BranchID)
        {
            if (!findMdiChildren("frmMessageBoard"))
            {
                frmMessageBoard fMessageBoard = new frmMessageBoard(BranchID);
                fMessageBoard.ShowDockEvent += new HRM.Utilities.ShowDock(ShowDock);
                fMessageBoard.RightToLeftLayout = true;
                fMessageBoard.Show(this.dockPanelHRM, WeifenLuo.WinFormsUI.Docking.DockState.DockRightAutoHide);
            }
        }

        //Khởi tạo danh sách ảnh để gán cho các menu, icon
        public static void InitResource()
        {
            FormGlobals.App_InitResource(typeof(HRM.Properties.Resources));
        }

        public static void InitResource(Type resource)
        {
            FormGlobals.App_InitResource(resource);
            FormGlobals.App_InitResource(typeof(HRM.Properties.Resources));
        }

        //Form load
        private void frmMain_Load(object sender, EventArgs e)
        {
            FormGlobals.dockPanel = this.dockPanelHRM;
            InitResource();
            FormGlobals.Menu_AutoSetIcon(mnuMain);

            //
            this.Refresh();
            Application.DoEvents();
            isFirstLoad = true;

            frmLogin f = new frmLogin();
            f.Owner = this;

            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //if (f.ShowDialog(this) == DialogResult.OK)
            {
                FormGlobals.ToolStrip_SetViewOnly(false, mnuChangePass, mnuProfile, mnuMaskWork, mnuPayRoll, mnuList, mnuReport, mnuRecruitmentManagement, mnuInsurance);
                //
                AuthenticUser();
                isFirstLoad = false;

                //Cập nhật phiên bản mới - nếu có
                if (HasNewVerion())
                    UpdateNewVersion();

                //Khởi tại các menu chức năng của hệ thống
                Init_Menu();
            }
            else
            {
                this.Close();
            }
        }

        //Gán quyền truy cập, ẩn hiện menu
        private void Init_Menu()
        {
            if (String.IsNullOrEmpty(Program.strUserName))
            {
                FormGlobals.ToolStrip_SetVisible(false, mnuUsers, mnuRoles, mnuLevel);
                FormGlobals.ToolStrip_SetViewOnly(true, mnuChangePass, mnuMaskWork, mnuProfile, mnuPayRoll, mnuList, mnuReport, mnuRecruitmentManagement, mnuInsurance, mnuImportData, mnuExcuteSQL);
            }
            //
            if (Program.strUserName.ToLower() == "phuhai")
                mnuChangePass.Enabled = false;
            mnuDonViQuanLy.Visible = (Program.isAdmin || Program.isChuyenQuan || (Program.strUserName.ToLower() == "vvtuy")) ? true : false;
            mnuMergebook.Visible = (Program.isAdmin || (Program.strUserName.ToLower() == "vvtuy")) ? true : false;
            switch (Program.intInsType)
            {
                case 0:
                    mnuInsuranceFactor.Visible = true;
                    mnuInsuranceSalary.Visible = false;
                    break;
                case 1:
                    mnuInsuranceFactor.Visible = false;
                    mnuInsuranceSalary.Visible = true;
                    break;
                case 2:
                    mnuInsuranceFactor.Visible = true;
                    mnuInsuranceSalary.Visible = true;
                    break;
            }
        }

        //Kiểm tra version để cập nhật
        int LastestVersion = 0;
        private bool HasNewVerion()
        {
            MtomClient wcfMtom = Service.Mtom();
            LastestVersion = wcfMtom.GetLastestVersion();
            wcfMtom.Close();
            return LastestVersion > Program.Version;
        }

        //Mở form download file để cập nhật
        private void UpdateNewVersion()
        {
            frmAutoUpdate frm = new frmAutoUpdate();
            frm.StartPosition = FormStartPosition.CenterParent;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("Phần mềm đã tải về phiên bản mới.\nHãy nhấn nút OK để bắt đầu cập nhật ngay", "SIS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //{
                    //Nếu đã cài được bản mới thì sẽ chạy RunUpdate, còn không thì chạy  AutoUpdate
                    //Từ bản mới mới có 

                    string sTempFolder = Path.GetTempPath() + "HRMUpdate";
                    string sAppFolder = Application.StartupPath;
                    string sExecFile = Path.Combine(sTempFolder, "AutoUpdate\\AutoUpdate.exe");
                    
                    //
                    //string sFileName = (File.Exists(Application.StartupPath + "\\AutoUpdate\\UpdateCalled.exe")) ?
                    //    "UpdateCalled.exe" : "AutoUpdate.exe";

                    System.Diagnostics.Process.Start(sExecFile, 
                        "1 " + sTempFolder.Trim().Replace(" ", "$$") //TempFolder
                        + " " + sAppFolder.Trim().Replace(" ", "$$")  //Application Folder
                        + " " + frm.FileList);


                    isFirstLoad = true;
                    Application.Exit();
                //}
            }
        }

        //Sau khi đã đăng nhập user, án các menu ương ứng -> có thể đổi bằng hàm set quyền riêng
        private void AuthenticUser()
        {
            //---Hệ thống---
            mnuUsers.Visible = mnuRoles.Visible = mnuExcuteSQL.Visible = mnuLevel.Visible = Program.isAdmin;
            mnuUsers.Visible = mnuExcuteSQL.Visible = mnuLevel.Visible = (Program.strUserName == "VVTUY" || Program.isAdmin);

            mnuEmployeeList.Enabled = UIParamater.Quyen_HoSoCanBo.View;
            //if (mnuEmployeeList.Enabled)
            //    mnuEmployeeList_Click(null, null);
            mnuLeaveWork.Enabled = UIParamater.Quyen_NgayNghiVaCongTac.View;
            mnuEmployeeShift.Enabled = UIParamater.Quyen_BangPhanCa.View;
            mnuScienceManagement.Enabled = UIParamater.Quyen_CacDeTaiKhoaHoc.View;
            mnuEducation.Enabled = UIParamater.Quyen_CacKhoaDaoTao.View;
            mnuIncreaseSalary.Enabled = UIParamater.Quyen_CanhBaoNangLuong.View;
            mnuFinishTenure.Enabled = UIParamater.Quyen_CanhBaoSapNghiHuu.View;
            mnuBirthDay.Enabled = UIParamater.Quyen_CanhBaoSapSinhNhat.View;

            mnuInsuranceFactor.Enabled = UIParamater.Quyen_PhatSinhBaoHiem.View;
            mnuInsuranceSalary.Enabled = UIParamater.Quyen_PhatSinhBaoHiem.View;


            mnuSalary.Enabled = UIParamater.Quyen_BangLuong.View;
            mnuOffered.Enabled = UIParamater.Quyen_DeNghiTroCap.View;
            mnuFundSalary.Enabled = UIParamater.Quyen_DoiChieuQuyBHXH.View;
            mnuInsPeriods.Enabled = UIParamater.Quyen_PhatSinhBaoHiem.View;

            mnuAdvancePayment.Enabled = UIParamater.Quyen_TamUngLuong.View;
            mnuLaterInsurance.Enabled = UIParamater.Quyen_TruyDongBHXH.View;
            mnuAward.Enabled = UIParamater.Quyen_KhenThuong.View;

            mnuRecruitment.Enabled = UIParamater.Quyen_DotTuyenDung.View;
            mnuCandidateList.Enabled = UIParamater.Quyen_UngVien.View;

            mnuSystemParameter.Visible = UIParamater.Quyen_ThamSoHeThong.View;
            mnuBranch.Enabled = UIParamater.Quyen_ChiNhanh.View;
            toolStripMenuItem3.Visible = UIParamater.Quyen_ChiNhanh.View;
            mnuDepartment.Enabled = UIParamater.Quyen_PhongBan.View;
            mnuPosition.Enabled = UIParamater.Quyen_ChucVu.View;
            mnuGrade.Enabled = UIParamater.Quyen_CapDo.View;
            mnuLanguage.Enabled = UIParamater.Quyen_NgoaiNgu.View;
            mnuEthnic.Enabled = UIParamater.Quyen_DanToc.View;
            mnuReligion.Enabled = UIParamater.Quyen_TonGiao.View;
            mnuMaritalStatus.Enabled = UIParamater.Quyen_TinhTrangHonNhan.View;
            mnuContractType.Enabled = UIParamater.Quyen_LoaiHopDong.View;
            mnuLeave.Enabled = UIParamater.Quyen_HinhThucNghi.View;
            mnuInterestRate.Enabled = UIParamater.Quyen_LaiSuatChamNop.View;
            mnuFeastday.Enabled = UIParamater.Quyen_NgayNghiTrongNam.View;
            mnuMaskWork.Enabled = UIParamater.Quyen_BangChamCong.View;

            mnuEmployeeReport.Enabled = UIParamater.Quyen_BaoCaoNhanSu.View;
            mnuCandidateReport.Enabled = UIParamater.Quyen_BaoCaoTuyenDung.View;
            mnuBHXH.Enabled = UIParamater.Quyen_BaoCaoBHXH.View;
            đềNghịHưởngTrợCấpToolStripMenuItem.Enabled = UIParamater.Quyen_BaoCaoHuongTroCap.View;
            mnuLevel.Enabled = UIParamater.Quyen_Bac.View;
            mnuHesoMucLuong.Enabled = UIParamater.Quyen_NgachBac.View;
            mnuEvaluation.Enabled = UIParamater.Quyen_TieuChiDanhGia.View;
            mnuStandard.Enabled = UIParamater.Quyen_TrinhDo.View;
            mnuTypeOfLeaveWork.Enabled = UIParamater.Quyen_HinhThucNghiViec.View;
            mnuSafetyDevice.Enabled = UIParamater.Quyen_ThietBiCCLD.View;
            mnuEmployeeNotActive.Enabled = UIParamater.Quyen_NhanVienNghiViec.View;
            mnuNational.Enabled = UIParamater.Quyen_QuocGia.View;
            mnuDeNghiCapSoBH.Enabled = UIParamater.Quyen_DeNghiCapSoBH.View;
            mnuEditbook.Enabled = UIParamater.Quyen_DieuChinhSoBH.View;
            mnuAmountFund.Visible = false;
            mnuUNC.Visible = UIParamater.Quyen_UNC.View;
            mnuImportData.Enabled = UIParamater.Quyen_ImportDuLieuCQBH.View;

            //Gán giá trị vào thanh status strip ở dứoi
            StatusStrip_SetText(tlbFullName, UIParamater.FullNameOfUser);
            StatusStrip_SetText(tltBranch, Program.strBranch);
            StatusStrip_SetText(tlbTotalEmp, Program.TotalEmployee.ToString());
            tlbServerAdd.Text = String.Format(tlbServerAdd.Text, Properties.Settings.Default.ServiceAddress);
            //
            int BranchID = 0;
            if (Program.isAdmin || Program.isViewAll)
                BranchID = 0;
            else
                BranchID = Program.intBranchID;
            //MessageBoard(BranchID);
        }

        #region SetLanguage

        private void cboLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cboLanguage.SelectedIndex)
            {
                case 0:
                    Program.strLanguage = "vi";
                    Thread.CurrentThread.CurrentUICulture = Program.m_VietnameseCulture;
                    break;
                case 1:
                    Program.strLanguage = "en";
                    Thread.CurrentThread.CurrentUICulture = Program.m_EnglishCulture;
                    break;
            }
            Properties.Settings.Default.Language = Program.strLanguage;
            Properties.Settings.Default.Save();
            //LoadLanguge();

        }

        private void LoadLanguge()
        {
            for (int i = 0; i < this.MdiChildren.Length; i++)
            {
                this.MdiChildren[i].Hide();
                this.MdiChildren[i].Show();
            }

            //if (this.Tag != null)
            //    this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_MenuStrip(ref mnuMain);
            UpdateUI.Load_ToolStripMenuItem(ref mnuSystem);
            UpdateUI.Load_ToolStripMenuItem(ref mnuProfile);
            UpdateUI.Load_ToolStripMenuItem(ref mnuMaskWork);
            UpdateUI.Load_ToolStripMenuItem(ref mnuPayRoll);
            UpdateUI.Load_ToolStripMenuItem(ref mnuRecruitmentManagement);
            UpdateUI.Load_ToolStripMenuItem(ref mnuList);
            UpdateUI.Load_ToolStripMenuItem(ref mnuReport);
            //UpdateUI.Load_ToolStripMenuItem(ref mnuHelp);
            UpdateUI.Load_ToolStripMenuItem(ref mnuInsurance);

        }
        #endregion

        #region Call MdiChildren

        private bool findMdiChildren(string formName)
        {
            bool val = false;
            for (int i = 0; i < this.MdiChildren.Length; i++)
            {
                if (this.MdiChildren[i].Name == formName)
                {
                    val = true;
                    this.MdiChildren[i].BringToFront();
                    break;
                }

            }
            return val;
        }

        private bool findMdiChildren(string formName, string formText)
        {
            bool val = false;
            for (int i = 0; i < this.MdiChildren.Length; i++)
            {
                if (this.MdiChildren[i].Name == formName && this.MdiChildren[i].Text == formText)
                {
                    val = true;
                    this.MdiChildren[i].BringToFront();
                    break;
                }
            }
            return val;
        }


        #endregion

        //Các sự kiện click trên menu
        #region Menu click event

        private void mnuShift_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmShiftList"))
            {
                frmShiftList f = new frmShiftList();
                f.Show(this.dockPanelHRM);
            }
        }



        private void mnuMarkWorking_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmMarkWork"))
            {
                frmMarkWork f = new frmMarkWork();
                f.Show(this.dockPanelHRM);
            }
        }









        private void mnuEmployeeReport_Click(object sender, EventArgs e)
        {

        }

        private void mnuDSLaoDongBHXH_Click(object sender, EventArgs e)
        {
            frmPreviewReport f = new frmPreviewReport("DSLaoDongBHXH", null);
            f.Show(this.dockPanelHRM);
        }

        private void danhSáchTruyĐóngBHXHBHYTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmPreviewReport f = new frmPreviewReport("TRUYDONG_BHXH", null);
            f.Show(this.dockPanelHRM);
        }

        private void mnurptDieuChinhLuongVaBHXH_Click(object sender, EventArgs e)
        {
        }

        private void bHToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }



        private void lnkHetHHD_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEmployeeLCInvalidList"))
            {
                frmEmployeeLCInvalidList f = new frmEmployeeLCInvalidList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void lnkSapHHD_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEmployeeLCNearInvalidList"))
            {
                frmEmployeeLCNearInvalidList f = new frmEmployeeLCNearInvalidList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void lklSapHetHanTV_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEmployeeLCNearProbationInvalidList"))
            {
                frmEmployeeLCNearProbationInvalidList f = new frmEmployeeLCNearProbationInvalidList();
                f.Show(this.dockPanelHRM);
            }
        }
        private void lnkChuaCoHD_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEmployeeNoLCList"))
            {
                frmEmployeeNoLCList f = new frmEmployeeNoLCList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuSalaryAllowance_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmSalaryAllowanceList"))
            {
                frmSalaryAllowanceList f = new frmSalaryAllowanceList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void lblUpdatePos_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmUpdatePositionList"))
            {
                frmUpdatePositionList f = new frmUpdatePositionList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuNoDept_Click(object sender, EventArgs e)
        {

        }

        private void ShowDock(string frmName)
        {
            switch (frmName)
            {
                case "frmIncreaseSalaryList":
                    if (!findMdiChildren("frmIncreaseSalaryList"))
                    {
                        frmIncreaseSalaryList f = new frmIncreaseSalaryList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
                case "frmUpdatePositionList":
                    if (!findMdiChildren("frmUpdatePositionList"))
                    {
                        frmUpdatePositionList f = new frmUpdatePositionList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
                case "frmEmployeeLCInvalidList":
                    if (!findMdiChildren("frmEmployeeLCInvalidList"))
                    {
                        frmEmployeeLCInvalidList f = new frmEmployeeLCInvalidList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
                case "frmEmployeeLCNearInvalidList":
                    if (!findMdiChildren("frmEmployeeLCNearInvalidList"))
                    {
                        frmEmployeeLCNearInvalidList f = new frmEmployeeLCNearInvalidList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
                case "frmEmployeeLCNearProbationInvalidList":
                    if (!findMdiChildren("frmEmployeeLCNearProbationInvalidList"))
                    {
                        frmEmployeeLCNearProbationInvalidList f = new frmEmployeeLCNearProbationInvalidList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
                case "frmEmployeeNoLCList":
                    if (!findMdiChildren("frmEmployeeNoLCList"))
                    {
                        frmEmployeeNoLCList f = new frmEmployeeNoLCList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
                case "frmEmployeeLCInvalidSpecialList":
                    if (!findMdiChildren("frmEmployeeLCInvalidSpecialList"))
                    {
                        frmEmployeeLCInvalidSpecialList f = new frmEmployeeLCInvalidSpecialList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
            }
        }

        private void frmMain_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F8:
                    if (!findMdiChildren("frmEmployeetmpList"))
                    {
                        frmEmployeetmpList f = new frmEmployeetmpList();
                        f.Show(this.dockPanelHRM);
                    }
                    break;
            }
        }

        private void lkProbation_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEmployeeProbationList"))
            {
                frmEmployeeProbationList f = new frmEmployeeProbationList();
                f.Show(this.dockPanelHRM);
            }
        }

        private string _SMSThongBaoPath = "";

        #endregion


        #region ReadTextFile
        //Khai báo bảng dữ liệu
        DataTable m_dtCSV;
        //Khai báo số lượng cột
        int m_iColumnCount;
        private void PopulateDataTableFromUploadedFile(string strm)
        {
            System.IO.StreamReader srdr = new System.IO.StreamReader(strm);
            String strLine = String.Empty;
            Int32 iLineCount = 0;
            do
            {
                strLine = srdr.ReadLine();
                if (strLine == null)
                {
                    break;
                }
                if (0 == iLineCount++)
                {
                    m_dtCSV = this.CreateDataTableForCSVData(strLine);
                }
                this.AddDataRowToTable(strLine, m_dtCSV);
            } while (true);
        }

        private DataTable CreateDataTableForCSVData(String strLine)
        {
            DataTable dt = new DataTable("CSVTable");
            String[] strVals = strLine.Split(new char[] { '\t' });
            m_iColumnCount = strVals.Length;
            int idx = 0;
            foreach (String strVal in strVals)
            {
                String strColumnName = String.Format("Column-{0}", idx++);
                dt.Columns.Add(strColumnName, Type.GetType("System.String"));
            }
            return dt;
        }

        private DataRow AddDataRowToTable(String strCSVLine, DataTable dt)
        {
            String[] strVals = strCSVLine.Split(new char[] { '\t' });
            Int32 iTotalNumberOfValues = strVals.Length;
            // If number of values in this line are more than the columns
            // currently in table, then we need to add more columns to table.
            if (iTotalNumberOfValues > m_iColumnCount)
            {
                Int32 iDiff = iTotalNumberOfValues - m_iColumnCount;
                for (Int32 i = 0; i < iDiff; i++)
                {
                    String strColumnName = String.Format("Column-{0}", (m_iColumnCount + i));
                    dt.Columns.Add(strColumnName, Type.GetType("System.String"));
                }
                m_iColumnCount = iTotalNumberOfValues;
            }
            int idx = 0;
            DataRow drow = dt.NewRow();
            foreach (String strVal in strVals)
            {
                String strColumnName = String.Format("Column-{0}", idx++);
                drow[strColumnName] = strVal.Trim();
            }
            dt.Rows.Add(drow);
            return drow;
        }


        private bool LoadCheckTime()
        {
            HRM.HRMServiceProxy.CheckTimeClient wsCheckTimeClient = Service.CheckTime();
            DataTable dt = m_dtCSV;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                HRM.HRMServiceProxy.CheckTimeInfo checktimeinfo = new CheckTimeInfo();
                checktimeinfo.CardNo = m_dtCSV.Rows[i]["Column-0"].ToString();
                checktimeinfo.Date = Convert.ToDateTime(m_dtCSV.Rows[i]["Column-1"]);
                checktimeinfo.IsInsert = false;
                checktimeinfo.Status = "";
                wsCheckTimeClient.CheckTime_Insert(checktimeinfo);
            }
            Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
            return true;
        }
        #endregion

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (!isFirstLoad)
            //    if (isFinishUpdate)
            //    {
            //        MessageBox.Show("Phần mềm đã cập nhật bản mới!\nHãy nhấn nút OK để bắt đầu cập nhật", "Thông báo");
            //        System.Diagnostics.Process.Start(Application.StartupPath + "\\autoupdate\\autoupdate.exe", "0 " + tempFolder.Trim().Replace(" ", "$$") + " " + fileList);
            //        isFirstLoad = true;
            //    }
            //    else if (MessageBox.Show("Bạn có chắc chắc muốn kết thúc phiên làm việc không?", UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)

            //        e.Cancel = true;
        }

        //Import data từ file excel
        frmProgressbar fProgressbar;
        void bgJ_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = ImportData(_Path, _FolderName);
        }
        void bgJ_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (Convert.ToBoolean(e.Result))
                MessageBox.Show(this, "Hoàn thành Import dữ liệu!");
            else
                MessageBox.Show(this, "Import dữ liệu bị lỗi!\nHãy thử lại");

            fProgressbar.Close();
        }
        string _Path = "";
        string _FileName = "";
        string[] _FolderName = null;
        bool ImportData(string PathName, string[] Folder)
        {
            bool retVal = true;
            int i = 0;
            int _HeaderID = 0;
            int _DetailID = 0;
            int _EmployeeID = 0;
            int _DepartmentID = 0;
            int _PositionID = 0;
            decimal _PaidAmount = 0;
            decimal _AmountRemain = 0;
            decimal _BHYT_PaidAmount = 0;
            decimal _BHTN_PaidAmount = 0;
            decimal _BHXH_PaidAmount = 0;
            decimal _BHYT_ThuaKyTruoc = 0;
            decimal _BHYT_ThieuKyTruoc = 0;
            decimal _BHTN_ThuaKyTruoc = 0;
            decimal _BHTN_ThieuKyTruoc = 0;
            decimal _BHXH_ThuaKyTruoc = 0;
            decimal _BHXH_ThieuKyTruoc = 0;
            _wcfEmployee = Service.Employee();
            PremiumClient _wcfPremium = Service.Premium();
            PremiumInfo _PremiumInfo;
            HeaderClient _wcfHeader = Service.Header();
            HeaderInfo _HeaderInfo;
            //_wcfDetail = Service.Detail();
            _wcfPD = Service.PositionDetail();
            PositionDetailInfo _PDInfo;
            HRM.HRMServiceProxy.LabourContractInfo _LCInfo;
            LabourContractClient _wcfLC = Service.LabourContract();

            SalaryFundClient _wcfFund = Service.SalaryFund();
            SalaryFundInfo _FundInfo;
            _wcfPosition = Service.Position();
            _wcfGrade = Service.Grade();
            DataSet dsHeader = new DataSet();
            _wcfDepartment = Service.Department();
            UNCClient _wcfUNC = Service.UNC();
            UNCInfo _UNCInfo;
            DataTable _dtLast = new DataTable();
            try
            {
                foreach (string _Name in Folder)
                {
                    //_FileName = openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\\") + 1);
                    _FileName = _Name.Substring(_Name.LastIndexOf("\\") + 1);
                    DataSet ds = new DataSet();
                    //OleDbConnection _Conn = new OleDbConnection("Provider = vfpoledb.1; Data Source = " + _Path + "; Collating Sequence=machine");
                    var _Conn = new OleDbConnection("Provider = vfpoledb.1; Data Source = " + _Path + "; Collating Sequence=machine");
                    var _dbCmd1 = new OleDbCommand();
                    var _dbCmd = new OleDbCommand("SELECT * FROM " + _FileName, _Conn);
                    if (_FileName == "HSC47.DBF")
                    {
                        _dbCmd1 = new OleDbCommand("SELECT DISTINCT keysl,madvi,maqt,ngayct,tyle_bhxh,tyle_bhyt,tyle_bhtn,mltt,loaidt FROM " + _FileName, _Conn);
                    }
                    else if ((_FileName == "QTBHXH.DBF"))
                    {
                        //_dbCmd = new OleDbCommand("SELECT sobhxh,hoten,madvi,tendvi,nghenghiep,loaidt,ma_nte,tuthang,denthang,val(str(ml)) as ml ,val(str(mlyt)) as mlyt,val(str(hsl)) as hsl,val(str(pc1)) as pc1,val(str(pc2)) as pc2,val(str(pc3)) as pc3,val(str(pc4)) as pc4,pa,ghichu FROM " + _FileName, _Conn);
                        _dbCmd = new OleDbCommand("SELECT sobhxh,hoten,madvi,tendvi,nghenghiep,loaidt,ma_nte,tuthang,denthang,cast(ml as numeric(10,3)) as ml ,cast(mlyt as numeric(10,3)) as mlyt,cast(hsl as numeric(10,3)) as hsl,cast(pc1 as numeric(10,3)) as pc1,cast(pc2 as numeric(10,3)) as pc2,cast(pc3 as numeric(10,3)) as pc3,cast(pc4 as numeric(10,3)) as pc4,pa,ghichu FROM " + _FileName, _Conn);
                    }
                    //try
                    //{
                    _Conn.Open();
                    var da = new OleDbDataAdapter(_dbCmd);
                    da.Fill(ds);
                    if (_FileName == "HSC47.DBF")
                    {
                        var da1 = new OleDbDataAdapter(_dbCmd1);
                        da1.Fill(dsHeader);
                    }
                    //}
                    //finally
                    //{
                    //    _Conn.Close();
                    //}
                    DataTable dtdept = _wcfDepartment.Department_GetAllWithBranch(Program.intBranchID).Tables[0];
                    if (dtdept.Rows.Count > 0)
                        _DepartmentID = Convert.ToInt32(dtdept.Rows[0]["DEPARTMENT_ID"]);

                    if (_FileName.Contains("HOSOCB.DBF") || _FileName.Contains("HOSOCN.DBF"))
                    {
                        //Insert bang HRM_Employee:
                        #region Ho so nhan vien
                        DataTable dtGrade = _wcfGrade.Grade_GetByBranch(Program.intBranchID).Tables[0];
                        int _GradeID = 0;
                        if (dtGrade.Rows.Count > 0)
                            _GradeID = Convert.ToInt32(dtGrade.Rows[0]["Grade_ID"]);

                        DataTable dtPos = _wcfPosition.Position_GetByBranchCode(Program.strBranchCode).Tables[0];
                        if (dtPos.Rows.Count > 0)
                            _PositionID = Convert.ToInt32(dtPos.Rows[0]["Position_ID"]);

                        try
                        {
                            //MessageBox.Show("Số nhân viên : " + SelectDistinct(_FileName, ds.Tables[0], "sobhxh").Rows.Count.ToString());

                            for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                _EmployeeID = 0;
                                _EmployeeInfo = new EmployeeInfo();
                                _EmployeeInfo.FirstName = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["Ten"].ToString().Trim());
                                _EmployeeInfo.LastName = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["Ho"].ToString().Trim());
                                _EmployeeInfo.CardNo = "";
                                int _Code = 0;
                                EmployeeInfo _empCode = new EmployeeInfo();
                                _empCode = _wcfEmployee.Employee_GetMaxEmployeeCode(Program.intBranchID);
                                if (_empCode == null)
                                    _Code = 0;
                                else
                                    _Code = Convert.ToInt32(_empCode.Code.Trim());
                                _EmployeeInfo.Code = (_Code + 1).ToString("00000");
                                _EmployeeInfo.Alias = "";
                                _EmployeeInfo.Education = 0;
                                if (ds.Tables[0].Rows[i]["ngaysinh"] != null)
                                    _EmployeeInfo.DateOfBirth = Convert.ToDateTime(ds.Tables[0].Rows[i]["ngaysinh"].ToString());
                                else
                                    _EmployeeInfo.DateOfBirth = DateTime.MinValue;
                                _EmployeeInfo.EthlicID = 1;//ds.Tables[0].Rows[i]["dantoc"].ToString()
                                _EmployeeInfo.MaterialStatusID = 1;
                                _EmployeeInfo.ReligionID = 1;
                                _EmployeeInfo.Sex = Convert.ToBoolean(ds.Tables[0].Rows[i]["gioitinh"]);
                                _EmployeeInfo.PlaceOfBirth = "";
                                _EmployeeInfo.Address = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["diachi"].ToString().Trim());
                                _EmployeeInfo.Phone = "";
                                _EmployeeInfo.Nationality = 1;

                                _EmployeeInfo.NativeCountry = "";

                                _EmployeeInfo.PassportNo = "";
                                _EmployeeInfo.PassportIssueDate = DateTime.MinValue;
                                _EmployeeInfo.PassportExpireDate = DateTime.MinValue;
                                _EmployeeInfo.IDCardNo = ds.Tables[0].Rows[i]["socmnd"].ToString().Trim();
                                if (ds.Tables[0].Rows[i]["ngaycmnd"] != null)
                                    _EmployeeInfo.IDCardIssueDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["ngaycmnd"].ToString());
                                else
                                    _EmployeeInfo.IDCardIssueDate = DateTime.MinValue;
                                _EmployeeInfo.IDCardIssueAuthority = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["noicap"].ToString().Trim());
                                _EmployeeInfo.SIBookNo = ds.Tables[0].Rows[i]["sobhxh"].ToString().Trim();


                                _EmployeeInfo.SIBookIssueDate = DateTime.MinValue;
                                _EmployeeInfo.SIBookIssueAuthority = ds.Tables[0].Rows[i]["ma_tinh"].ToString().Trim();
                                _EmployeeInfo.BankAccountNo = "";
                                _EmployeeInfo.BankName = "";
                                _EmployeeInfo.StartDate = DateTime.MinValue;
                                _EmployeeInfo.EndDate = DateTime.MinValue;
                                _EmployeeInfo.Description = "";
                                _EmployeeInfo.IsOfficer = true;
                                _EmployeeInfo.IsQuit = false;
                                _EmployeeInfo.MedicalNo = ds.Tables[0].Rows[i]["sokcb"].ToString().Trim();
                                _EmployeeInfo.MedicalDate = DateTime.MinValue;
                                _EmployeeInfo.MedicalPlace = ds.Tables[0].Rows[i]["ma_bv"].ToString().Trim();
                                _EmployeeInfo.Type = true;
                                _EmployeeInfo.LeaveWorkID = 0;
                                _EmployeeInfo.UnemployIns = false;
                                _EmployeeInfo.UnemployInsDate = DateTime.MinValue;
                                _EmployeeInfo.Specialist = "";
                                _EmployeeInfo.Culture = "";
                                _EmployeeInfo.IsInitial = true;
                                _EmployeeInfo.PartyDate = DateTime.MinValue;
                                _EmployeeInfo.ArmyFromDate = DateTime.MinValue;
                                _EmployeeInfo.ArmyToDate = DateTime.MinValue;
                                _EmployeeInfo.ArmyPosition = "";
                                _EmployeeInfo.BranchID = Program.intBranchID;

                                if (_wcfEmployee.Employee_CheckExist(0, _EmployeeInfo.Code, Program.intBranchID) == 0)
                                {
                                    if (_wcfEmployee.Employee_CheckExistSIBookNo(0, _EmployeeInfo.SIBookNo, Program.intBranchID) == 0)
                                    {
                                        //_EmployeeID = _wcfEmployee.Employee_Insert(_EmployeeInfo);
                                        _EmployeeID = _wcfEmployee.Employee_Import(_EmployeeInfo);

                                        //Do insert nếu ko phải là số sổ thật thì sẽ sinh số sổ tạm => cần update lại số sổ theo đúng như file


                                        //Insert vị trí 

                                        _PDInfo = new PositionDetailInfo();
                                        _PDInfo.DepartmentID = _DepartmentID;
                                        _PDInfo.EmployeeID = _EmployeeID;
                                        if (ds.Tables[0].Columns.Contains("thang"))
                                            _PDInfo.BeginDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["thang"].ToString().Substring(4, 2) + "/" + ds.Tables[0].Rows[i]["thang"].ToString().Substring(0, 4));
                                        else
                                            _PDInfo.BeginDate = DateTime.Now.Date;
                                        _PDInfo.EndDate = DateTime.MinValue;
                                        _PDInfo.IsActive = true;
                                        _PDInfo.PositionID = _PositionID;
                                        _PDInfo.PositionAllowance = 0;
                                        _PDInfo.TotalSalary = 0;
                                        _PDInfo.DateSalary = DateTime.MinValue;
                                        _PDInfo.GradeID = _GradeID;
                                        _PDInfo.LevelID = 1;
                                        _PDInfo.MinSalary = 0;
                                        if (ds.Tables[0].Columns.Contains("ml"))
                                        {
                                            _PDInfo.BasicSalary = Convert.ToDecimal(ds.Tables[0].Rows[i]["ml"].ToString());
                                        }
                                        else
                                        {
                                            _PDInfo.BasicSalary = 0;
                                        }
                                        if (ds.Tables[0].Columns.Contains("hsl"))
                                        {
                                            _PDInfo.BasicFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["hsl"].ToString());
                                            _PDInfo.PositionFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc1"].ToString());
                                            _PDInfo.OverFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc2"].ToString());
                                            _PDInfo.JobFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc3"].ToString());
                                            _PDInfo.AreaFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc4"].ToString());
                                        }
                                        else
                                        {
                                            _PDInfo.BasicFactor = 0;
                                            _PDInfo.PositionFactor = 0;
                                            _PDInfo.OverFactor = 0;
                                            _PDInfo.JobFactor = 0;
                                            _PDInfo.AreaFactor = 0;
                                        }
                                        _PDInfo.OtherFactor = 0;
                                        _PDInfo.PositionAllowance = 0;
                                        _PDInfo.LunchAllowance = 0;
                                        _PDInfo.TelephoneAllowance = 0;
                                        _PDInfo.LaterInsurance = false;
                                        _PDInfo.Job = "";
                                        _PDInfo.DatePositionBegin = DateTime.MinValue;
                                        _PDInfo.DatePositionEnd = DateTime.MinValue;
                                        _PDInfo.Description = "";
                                        _wcfPD.PositionDetail_Insert(_PDInfo);


                                        //Insert hợp đồng mặc định, để có phòng ban
                                        //Hợp đồng
                                        _LCInfo = new LabourContractInfo();
                                        _LCInfo.DepartmentID = _DepartmentID;
                                        _LCInfo.EmployeeID = _EmployeeID;
                                        _LCInfo.PositionID = _PositionID;
                                        _LCInfo.IsActive = true;
                                        //
                                        _wcfLC.LabourContract_Insert(_LCInfo);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        #endregion
                    }
                    else if (_FileName.Contains("HSC47.DBF"))
                    {
                        //try
                        //{
                        #region Cap nhat tang giam BHXH
                        string sTmp = "";
                        foreach (DataRow drHeader in dsHeader.Tables[0].Rows)
                        {
                            //Insert bang HRM_Header:
                            _HeaderID = 0;
                            _HeaderInfo = new HeaderInfo();
                            _HeaderInfo.BranhCode = drHeader["madvi"].ToString().Trim();

                            _HeaderInfo.Date = new DateTime(Convert.ToDateTime(drHeader["ngayct"].ToString()).Year, Convert.ToDateTime(drHeader["ngayct"].ToString()).Month, Convert.ToDateTime(drHeader["ngayct"].ToString()).Day);

                            _HeaderInfo.Month = Convert.ToInt32(drHeader["maqt"].ToString().Substring(4, 2));
                            _HeaderInfo.Year = Convert.ToInt32(drHeader["maqt"].ToString().Substring(0, 4));
                            _HeaderInfo.Period = Convert.ToInt32(drHeader["maqt"].ToString().Substring(6, 2));
                            _HeaderInfo.Social = Convert.ToDecimal(drHeader["tyle_bhxh"]);
                            _HeaderInfo.Medical = Convert.ToDecimal(drHeader["tyle_bhyt"]);
                            _HeaderInfo.Unemployed = Convert.ToDecimal(drHeader["tyle_bhtn"]);
                            _HeaderInfo.BasicSalary = Convert.ToDecimal(drHeader["mltt"]);
                            _HeaderInfo.IsInitial = true;
                            _HeaderInfo.Type = Convert.ToString(drHeader["loaidt"]);

                            if (Convert.ToInt32(drHeader["maqt"].ToString().Substring(0, 4)) == 2011)
                            {
                                sTmp = "asdasd";
                            }

                            if (!_wcfHeader.Header_CheckExist(0, _HeaderInfo.BranhCode, _HeaderInfo.Date, _HeaderInfo.Month, _HeaderInfo.Year, _HeaderInfo.Period, _HeaderInfo.Type))
                            {
                                _HeaderID = _wcfHeader.Header_Insert(_HeaderInfo);
                                DataRow[] _drDetail = null;
                                _drDetail = ds.Tables[0].Select("keysl='" + drHeader["keysl"].ToString().Trim() + "'");

                                //MessageBox.Show("Số bản ghi phát sinh : " + _drDetail.Length.ToString());

                                foreach (DataRow dr in _drDetail)
                                {
                                    //Insert bang HRM_Detail:
                                    _DetailID = 0;
                                    _DetailInfo = new DetailInfo();
                                    _EmployeeInfo = new EmployeeInfo();
                                    _DetailInfo.Detail_Documentid = _HeaderID;
                                    _DetailInfo.Detail_Insbookno = dr["sobhxh"].ToString().Trim();
                                    _EmployeeInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(_DetailInfo.Detail_Insbookno);
                                    if (_EmployeeInfo != null)
                                        _DetailInfo.Detail_Employeecode = _EmployeeInfo.Code;
                                    else
                                        _DetailInfo.Detail_Employeecode = "";
                                    _DetailInfo.Detail_Fromdate = Convert.ToDateTime(dr["tuthang"].ToString().Trim().Substring(4, 2) + "/" + dr["tuthang"].ToString().Trim().Substring(0, 4));
                                    _DetailInfo.Detail_Todate = Convert.ToDateTime(dr["denthang"].ToString().Trim().Substring(4, 2) + "/" + dr["denthang"].ToString().Trim().Substring(0, 4));
                                    _DetailInfo.Detail_Instypecode = dr["pa"].ToString().Trim();
                                    _DetailInfo.Detail_Socialrate = Convert.ToDecimal(dr["tyle_bhxhd"]);
                                    _DetailInfo.Detail_Medicalrate = Convert.ToDecimal(dr["tyle_bhytd"]);
                                    _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal(dr["tyle_bhtnd"]);
                                    _DetailInfo.Detail_Oldbasicfactor = Convert.ToDecimal(dr["hsl_dk"]);
                                    _DetailInfo.Detail_Oldpositionfactor = Convert.ToDecimal(dr["pc1_dk"]);
                                    _DetailInfo.Detail_Oldoverfactor = Convert.ToDecimal(dr["pc2_dk"]);
                                    _DetailInfo.Detail_Oldjobfactor = Convert.ToDecimal(dr["pc3_dk"]);
                                    _DetailInfo.Detail_Oldareafactor = Convert.ToDecimal(dr["pc4_dk"]);
                                    _DetailInfo.Detail_Newbasicfactor = Convert.ToDecimal(dr["hsl"]);
                                    _DetailInfo.Detail_Newpositionfactor = Convert.ToDecimal(dr["pc1"]);
                                    _DetailInfo.Detail_Newoverfactor = Convert.ToDecimal(dr["pc2"]);
                                    _DetailInfo.Detail_Newjobfactor = Convert.ToDecimal(dr["pc3"]);
                                    _DetailInfo.Detail_Newareafactor = Convert.ToDecimal(dr["pc4"]);
                                    _DetailInfo.Detail_Regioncode = dr["ma_tinh"].ToString().Trim();
                                    _DetailInfo.Detail_Hospitalcode = dr["ma_bv"].ToString().Trim();
                                    _DetailInfo.Detail_Newamount = Convert.ToDecimal(dr["ml"]);
                                    _DetailInfo.Detail_Oldamount = Convert.ToDecimal(dr["ml_dk"]);
                                    _DetailInfo.Detail_Type = dr["loaidt"].ToString().Trim();
                                    _DetailInfo.Detail_Takecard = Convert.ToBoolean(dr["the_bhyt"]);

                                    //convert tất cả font chữ từ TCVN3 -> Unicode
                                    _DetailInfo.Detail_Description = String.Empty;
                                    _DetailInfo.Detail_PositionName = UnicodeConvert.TCVN3ToUnicode(Convert.ToString(dr["congviec"]));
                                    _DetailInfo.Detail_Status = 1;
                                    //Tính số tháng:
                                    //Nếu From = To --> Số tháng = 0
                                    //Nếu From < To AND To = Tháng đang phát sinh --> Số tháng = To - From
                                    //Nếu From < To AND To < Tháng đang phát sinh --> Số tháng = To - From + 1
                                    if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate)
                                        _DetailInfo.Detail_Totalmonth = 0;
                                    else if (_DetailInfo.Detail_Fromdate < _DetailInfo.Detail_Todate && _DetailInfo.Detail_Todate.Month == _HeaderInfo.Month && _DetailInfo.Detail_Todate.Year == _HeaderInfo.Year)
                                        _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate);
                                    else if (_DetailInfo.Detail_Fromdate < _DetailInfo.Detail_Todate && _DetailInfo.Detail_Todate.Month < _HeaderInfo.Month && _DetailInfo.Detail_Todate.Year <= _HeaderInfo.Year)
                                        _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate) + 1;
                                    else
                                        _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate) + 1;

                                    //
                                    //if (!_wcfDetail.Detail_Exist(0, _DetailInfo.InsBookNo, _DetailInfo.FromDate, _DetailInfo.ToDate, _DetailInfo.InsTypeCode, _DetailInfo.OldAmount, _DetailInfo.OldBasicFactor, _DetailInfo.OldPositionFactor, _DetailInfo.OldOverFactor, _DetailInfo.OldJobFactor, _DetailInfo.NewAmount, _DetailInfo.NewBasicFactor, _DetailInfo.NewPositionFactor, _DetailInfo.NewOverFactor, _DetailInfo.NewJobFactor))
                                    //    _DetailID = _wcfDetail.Detail_Insert(_DetailInfo);
                                    if (!Detail_Controller.Instance().Detail_Exist(0, _DetailInfo.Detail_Insbookno, _DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate, _DetailInfo.Detail_Instypecode, _DetailInfo.Detail_Oldamount, _DetailInfo.Detail_Oldbasicfactor, _DetailInfo.Detail_Oldpositionfactor, _DetailInfo.Detail_Oldoverfactor, _DetailInfo.Detail_Oldjobfactor, _DetailInfo.Detail_Newamount, _DetailInfo.Detail_Newbasicfactor, _DetailInfo.Detail_Newpositionfactor, _DetailInfo.Detail_Newoverfactor, _DetailInfo.Detail_Newjobfactor))
                                        _DetailID = Detail_Controller.Instance().Detail_Insert(_DetailInfo);
                                }
                            }
                        }
                        //Cap nhat nhan vien nghi viec:
                        MainServiceClient _wcfMain = Service.MainService();
                        string _sqlString = "";
                        _sqlString = "UPDATE HRM_Employee SET Employee_Isquited=1";
                        _sqlString = _sqlString + " WHERE Employee_SIBookNo IN ";
                        _sqlString = _sqlString + " (SELECT Detail_InsBookNo FROM vw_HRM_BHXH WHERE Detail_InsTypeCode IN ('GH') AND Document_BranchCode = '" + Program.strBranchBHXH + "')";
                        _wcfMain.ExecuteQuery(_sqlString);
                        #endregion
                        //}
                        //catch (Exception ex)
                        //{
                        //    string error = ex.ToString();
                        //}
                    }
                    
                    //else if (_FileName.Contains("HISTORY") || _FileName.Contains("QTBHXH"))
                    //else if (_FileName.Contains("QTBHXH.DBF"))
                    else if (_FileName.Contains("HISTORY.DBF"))
                    //070915: hiepdh, chỉ lấy QT trước đây từ Premium thôi
                    {
                        //try
                        //{
                        #region Qua trinh tham gia truoc day
                        for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            //Insert bang HRM_Premium:u
                            _PremiumInfo = new PremiumInfo();
                            _PremiumInfo.SIBookNo = ds.Tables[0].Rows[i]["sobhxh"].ToString().Trim();

                            EmployeeInfo emplObj = _wcfEmployee.Employee_GetInfoBySIBookNo(_PremiumInfo.SIBookNo);
                            if (emplObj != null)
                                _PremiumInfo.EmployeeID = emplObj.ID;
                            else
                            {
                                string s = _PremiumInfo.SIBookNo;
                            }

                            if (_FileName.Contains("HISTORY"))
                            {
                                _PremiumInfo.FromDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["tuthang"].ToString().Substring(4, 2) + "/" + ds.Tables[0].Rows[i]["tuthang"].ToString().Substring(0, 4));
                                _PremiumInfo.ToDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["denthang"].ToString().Substring(4, 2) + "/" + ds.Tables[0].Rows[i]["denthang"].ToString().Substring(0, 4));
                            }
                            else
                            {
                                _PremiumInfo.FromDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["tuthang"].ToString().Substring(0, 2) + "/" + ds.Tables[0].Rows[i]["tuthang"].ToString().Substring(2, 4));
                                _PremiumInfo.ToDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["denthang"].ToString().Substring(0, 2) + "/" + ds.Tables[0].Rows[i]["denthang"].ToString().Substring(2, 4));
                            }
                            _PremiumInfo.WorkUnit = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["madvi"].ToString().Trim());
                            _PremiumInfo.WorkName = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["tendvi"].ToString().Trim());
                            _PremiumInfo.Job = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["nghenghiep"].ToString().Trim());
                            _PremiumInfo.Type = ds.Tables[0].Rows[i]["loaidt"].ToString().Trim();
                            _PremiumInfo.Salary = Convert.ToDecimal(ds.Tables[0].Rows[i]["ml"]);
                            _PremiumInfo.BasicSalary = 0;
                            _PremiumInfo.BasicFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["hsl"]);
                            _PremiumInfo.PositionFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc1"]);
                            _PremiumInfo.OverSeniorityFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc2"]);
                            _PremiumInfo.SeniorityFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc3"]);
                            _PremiumInfo.AreaFactor = Convert.ToDecimal(ds.Tables[0].Rows[i]["pc4"]);
                            DateTime _FromDate = _PremiumInfo.FromDate;
                            DateTime _ToDate = _PremiumInfo.ToDate;
                            _PremiumInfo.MonthNo = UISetting.GetMonth(_FromDate, _ToDate) + 1;
                            if (ds.Tables[0].Rows[i]["pa"].ToString().Trim().Length == 0)
                                _PremiumInfo.InsTypeCode = "0";
                            else
                                _PremiumInfo.InsTypeCode = ds.Tables[0].Rows[i]["pa"].ToString().Trim();
                            _PremiumInfo.Description = UnicodeConvert.TCVN3ToUnicode(ds.Tables[0].Rows[i]["ghichu"].ToString().Trim());
                            _PremiumInfo.IsInitial = true;
                            _PremiumInfo.DateVal = Convert.ToDateTime("01/01/2000");

                            try
                            {
                                if (!_wcfPremium.Premium_Exist(0, _PremiumInfo.SIBookNo, _PremiumInfo.FromDate, _PremiumInfo.ToDate))
                                    _wcfPremium.Premium_Insert(_PremiumInfo);
                            }
                            catch (Exception ex)
                            {
                                string s = "abc";
                            }
                        }
                        #endregion
                        //}
                        //catch (Exception ex)
                        //{
                        //    string error = ex.ToString();
                        //    MessageBox.Show(error);
                        //}
                    }
                    else if (_FileName.Contains("S53_DTL.DBF"))
                    {

                        #region Ket qua dong BHXH
                        for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            try
                            {
                                //Insert bang HRM_Premium:
                                _FundInfo = new SalaryFundInfo();
                                _FundInfo.BranchCode = ds.Tables[0].Rows[i]["madvi"].ToString().Trim();
                                _FundInfo.Month = Convert.ToDateTime(ds.Tables[0].Rows[i]["thang"].ToString().Substring(4, 2) + "/" + ds.Tables[0].Rows[i]["thang"].ToString().Substring(0, 4));
                                _FundInfo.Quater = ds.Tables[0].Rows[i]["quy"].ToString().Substring(4, 1) + "/" + ds.Tables[0].Rows[i]["quy"].ToString().Substring(0, 4);

                                //Lay du lieu thang truoc chuyen sang:
                                _dtLast = _wcfFund.SalaryFund_GetLastData(_FundInfo.Month.Month, _FundInfo.Month.Year, _FundInfo.BranchCode).Tables[0];
                                if (_dtLast.Rows.Count > 0)
                                {
                                    _BHYT_ThuaKyTruoc = Convert.ToDecimal(_dtLast.Rows[0]["SalaryFund_BHYTThua"]);
                                    _BHYT_ThieuKyTruoc = Convert.ToDecimal(_dtLast.Rows[0]["SalaryFund_BHYTThieu"]);
                                    _BHTN_ThuaKyTruoc = Convert.ToDecimal(_dtLast.Rows[0]["SalaryFund_BHTNThua"]);
                                    _BHTN_ThieuKyTruoc = Convert.ToDecimal(_dtLast.Rows[0]["SalaryFund_BHTNThieu"]);
                                    _BHXH_ThuaKyTruoc = Convert.ToDecimal(_dtLast.Rows[0]["SalaryFund_BHXHThua"]);
                                    _BHXH_ThieuKyTruoc = Convert.ToDecimal(_dtLast.Rows[0]["SalaryFund_BHXHThieu"]);
                                }
                                else
                                {
                                    _BHYT_ThuaKyTruoc = 0;
                                    _BHYT_ThieuKyTruoc = 0;
                                    _BHTN_ThuaKyTruoc = 0;
                                    _BHTN_ThieuKyTruoc = 0;
                                    _BHXH_ThuaKyTruoc = 0;
                                    _BHXH_ThieuKyTruoc = 0;
                                }

                                //Lay so tien da nop o bang UNC:
                                _PaidAmount = _wcfUNC.UNC_GetAmountPaid(_FundInfo.Month.Month, _FundInfo.Month.Year, _FundInfo.BranchCode);
                                //_PaidAmount = _PaidAmount + _BHYT_ThuaKyTruoc + _BHTN_ThuaKyTruoc + _BHXH_ThuaKyTruoc;
                                //_PaidAmount = 0;
                                //BHYT:
                                _FundInfo.BHYT_Amount = Convert.ToDecimal(ds.Tables[0].Rows[i]["tqlyt"].ToString());

                                _FundInfo.BHYT_Employee = UISetting.GetIntNo(ds.Tables[0].Rows[i]["sld"].ToString());
                                _FundInfo.BHYT_HaveToPaid = Convert.ToDecimal(ds.Tables[0].Rows[i]["pt_bhyt"]);
                                _FundInfo.BHYT_Increase = Convert.ToDecimal(ds.Tables[0].Rows[i]["bst_bhyt"]);
                                _FundInfo.BHYT_Decrease = Convert.ToDecimal(ds.Tables[0].Rows[i]["bsg_bhyt"]);
                                _FundInfo.BHYT_KyTruocThua = _BHYT_ThuaKyTruoc;
                                _FundInfo.BHYT_KyTruocThieu = _BHYT_ThieuKyTruoc;
                                _FundInfo.BHYT_Sum = _FundInfo.BHYT_HaveToPaid + _FundInfo.BHYT_Increase - _FundInfo.BHYT_Decrease + _BHYT_ThieuKyTruoc - _BHYT_ThuaKyTruoc;


                                if (_PaidAmount >= _FundInfo.BHYT_Sum)
                                {
                                    _BHYT_PaidAmount = _FundInfo.BHYT_Sum;
                                    _AmountRemain = _PaidAmount - _BHYT_PaidAmount;
                                }
                                else
                                {
                                    _BHYT_PaidAmount = _PaidAmount;
                                    _AmountRemain = 0;
                                }
                                _FundInfo.BHYT_PaidAmount = _BHYT_PaidAmount;
                                if (_FundInfo.BHYT_PaidAmount <= _FundInfo.BHYT_Sum)
                                    _FundInfo.BHYT_Thieu = _FundInfo.BHYT_Sum - _FundInfo.BHYT_PaidAmount;
                                else
                                    _FundInfo.BHYT_Thua = _FundInfo.BHYT_PaidAmount - _FundInfo.BHYT_Sum;

                                //BHTN:
                                _FundInfo.BHTN_Amount = Convert.ToDecimal(ds.Tables[0].Rows[i]["tqltn"].ToString());
                                if (_FundInfo.BHTN_Amount > 0)
                                {
                                    if (ds.Tables[0].Columns.Contains("sldtn"))
                                        _FundInfo.BHTN_Employee = UISetting.GetIntNo(ds.Tables[0].Rows[i]["sldtn"].ToString());
                                    else
                                        _FundInfo.BHTN_Employee = UISetting.GetIntNo(ds.Tables[0].Rows[i]["sld"].ToString());
                                }
                                else
                                    _FundInfo.BHTN_Employee = 0;
                                _FundInfo.BHTN_HaveToPaid = Convert.ToDecimal(ds.Tables[0].Rows[i]["pt_bhtn"]);
                                _FundInfo.BHTN_Increase = Convert.ToDecimal(ds.Tables[0].Rows[i]["bst_bhtn"]);
                                _FundInfo.BHTN_Decrease = Convert.ToDecimal(ds.Tables[0].Rows[i]["bsg_bhtn"]);
                                _FundInfo.BHTN_KyTruocThua = _BHTN_ThuaKyTruoc;
                                _FundInfo.BHTN_KyTruocThieu = _BHTN_ThieuKyTruoc;
                                _FundInfo.BHTN_Sum = _FundInfo.BHTN_HaveToPaid + _FundInfo.BHTN_Increase - _FundInfo.BHTN_Decrease + _BHTN_ThieuKyTruoc - _BHTN_ThuaKyTruoc;


                                if (_AmountRemain >= _FundInfo.BHTN_Sum)
                                {
                                    _BHTN_PaidAmount = _FundInfo.BHTN_Sum;
                                    _AmountRemain = _AmountRemain - _BHTN_PaidAmount;
                                }
                                else if (_FundInfo.BHTN_Amount == 0)
                                {
                                    //_BHTN_PaidAmount = _PaidAmount;
                                    //_AmountRemain = 0;
                                }

                                _FundInfo.BHTN_PaidAmount = _BHTN_PaidAmount;
                                if (_FundInfo.BHTN_PaidAmount <= _FundInfo.BHTN_Sum)
                                    _FundInfo.BHTN_Thieu = _FundInfo.BHTN_Sum - _FundInfo.BHTN_PaidAmount;
                                else
                                    _FundInfo.BHTN_Thua = _FundInfo.BHTN_PaidAmount - _FundInfo.BHTN_Sum;

                                //BHXH:
                                _FundInfo.BHXH_Amount = Convert.ToDecimal(ds.Tables[0].Rows[i]["tql"].ToString());
                                _FundInfo.BHXH_Employee = UISetting.GetIntNo(ds.Tables[0].Rows[i]["sld"].ToString());
                                _FundInfo.BHXH_HaveToPaid = Convert.ToDecimal(ds.Tables[0].Rows[i]["pt_bhxh"]);
                                _FundInfo.BHXH_Increase = Convert.ToDecimal(ds.Tables[0].Rows[i]["bst_bhxh"]);
                                _FundInfo.BHXH_Decrease = Convert.ToDecimal(ds.Tables[0].Rows[i]["bsg_bhxh"]);
                                _FundInfo.BHXH_KyTruocThua = _BHXH_ThuaKyTruoc;
                                _FundInfo.BHXH_KyTruocThieu = _BHXH_ThieuKyTruoc;
                                _FundInfo.BHXH_Sum = _FundInfo.BHXH_HaveToPaid + _FundInfo.BHXH_Increase - _FundInfo.BHXH_Decrease + _BHXH_ThieuKyTruoc - _BHXH_ThuaKyTruoc;

                                _BHXH_PaidAmount = _AmountRemain;
                                _FundInfo.BHXH_PaidAmount = _BHXH_PaidAmount;
                                if (_FundInfo.BHXH_PaidAmount <= _FundInfo.BHXH_Sum)
                                    _FundInfo.BHXH_Thieu = _FundInfo.BHXH_Sum - _FundInfo.BHXH_PaidAmount;
                                else
                                    _FundInfo.BHXH_Thua = _FundInfo.BHXH_PaidAmount - _FundInfo.BHXH_Sum;

                                _FundInfo.PhatKyTruoc = 0;
                                _FundInfo.PhatKyNay = 0;
                                _FundInfo.PhatDaNop = 0;
                                _FundInfo.PhatKySau = 0;
                                _FundInfo.IsApproved = 1;

                                if (_wcfFund.SalaryFund_CheckExist(0, Program.strBranchBHXH, _FundInfo.Quater, _FundInfo.Month) <= 0)
                                    _wcfFund.SalaryFund_Insert(_FundInfo);

                        #endregion
                            }
                            catch (Exception ex)
                            {
                                string error = ex.ToString();
                            }
                        }
                    }
                    else if (_FileName.Contains("UNC.DBF"))
                    {
                        //try{
                        #region Ủy nhiệm chi
                        for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            //Insert bang HRM_Premium:
                            _UNCInfo = new UNCInfo();
                            _UNCInfo.BranchCode = ds.Tables[0].Rows[i]["madvi"].ToString().Trim();
                            _UNCInfo.No = ds.Tables[0].Rows[i]["sophieu"].ToString().Trim();
                            _UNCInfo.Date = Convert.ToDateTime(ds.Tables[0].Rows[i]["ngay"].ToString().Trim());
                            _UNCInfo.Quater = ds.Tables[0].Rows[i]["quy"].ToString().Substring(4, 1) + "/" + ds.Tables[0].Rows[i]["quy"].ToString().Substring(0, 4);
                            _UNCInfo.Month = UISetting.GetIntNo(ds.Tables[0].Rows[i]["thang"].ToString().Substring(4, 2));
                            _UNCInfo.Year = UISetting.GetIntNo(ds.Tables[0].Rows[i]["thang"].ToString().Substring(0, 4));
                            _UNCInfo.Content = ds.Tables[0].Rows[i]["noidung"].ToString().Trim();
                            _UNCInfo.Amount = Convert.ToDecimal(ds.Tables[0].Rows[i]["tien_vnd"]);
                            _UNCInfo.Discription = ds.Tables[0].Rows[i]["ghichus"].ToString().Trim();
                            if (!_wcfUNC.UNC_CheckExist(0, Program.strBranchBHXH, _UNCInfo.Date, _UNCInfo.No))
                                _wcfUNC.UNC_Insert(_UNCInfo);
                        }
                        #endregion
                        //}
                        //catch (Exception ex)
                        //{
                        //    string error = ex.ToString();
                        //    MessageBox.Show(error);
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                retVal = false;
            }
            return retVal;
        }


        void f_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (var frm in (List<Form>)((frmPremiumList)(sender)).Tag)
                frm.Close();
        }

        void InputData(string _FileName)
        {
            int positionId = 0;
            int _EmployeeID = 0;
            int departmentId = 0;
            int i = 0;
            int n = 0;
            int _HeaderID = 0;
            int _DetailID = 0;
            string _FirstName = "";
            string _LastName = "";
            string _FullName = "";
            string col = "";
            _wcfGrade = Service.Grade();
            _wcfPosition = Service.Position();
            _wcfEmployee = Service.Employee();
            _wcfPD = Service.PositionDetail();
            _wcfDepartment = Service.Department();
            _wcfHeader = Service.Header();
            //_wcfDetail = Service.Detail();

            var ds = ReadExcelFile.ReadExcelList(_FileName);
            var dt = ds.Tables[0];

            var dtGrade = _wcfGrade.Grade_GetByBranch(Program.intBranchID).Tables[0];
            var gradeId = 0;
            if (dtGrade.Rows.Count > 0)
                gradeId = Convert.ToInt32(dtGrade.Rows[0]["Grade_ID"]);
            var dtPos = _wcfPosition.Position_GetByBranchCode(Program.strBranchCode).Tables[0];
            if (dtPos.Rows.Count > 0)
                positionId = Convert.ToInt32(dtPos.Rows[0]["Position_ID"]);
            foreach (DataRow dr in dt.Rows)
            {
                //Insert ho so:
                _EmployeeInfo = new EmployeeInfo();

                col = "HOTEN";
                _FullName = UnicodeConvert.TCVN3ToUnicode(Convert.ToString(dr[col]).Trim());
                n = _FullName.Length;
                i = _FullName.LastIndexOf(' ');
                _FileName = _FullName.Substring(i, n - i);
                _LastName = _FullName.Substring(0, i);
                _EmployeeInfo.FirstName = _FileName.Trim();
                _EmployeeInfo.LastName = _LastName.Trim();
                _EmployeeInfo.CardNo = "";
                var empCode = _wcfEmployee.Employee_GetMaxEmployeeCode(Program.intBranchID);
                var code = empCode == null ? 0 : Convert.ToInt32(empCode.Code.Trim());
                _EmployeeInfo.Code = (code + 1).ToString("00000");
                _EmployeeInfo.Alias = "";
                _EmployeeInfo.Education = 0;

                col = "NGAYSINH";
                if (dr[col].ToString().Trim().Length > 0)
                    _EmployeeInfo.DateOfBirth = UISetting.GetDate(dr[col].ToString().Trim());

                _EmployeeInfo.EthlicID = 1;//ds.Tables[0].Rows[i]["dantoc"].ToString()
                _EmployeeInfo.MaterialStatusID = 1;
                _EmployeeInfo.ReligionID = 1;

                col = "GIOITINH";
                if (dr[col].ToString().Trim() == "X")
                    _EmployeeInfo.Sex = false;
                else
                    _EmployeeInfo.Sex = true;

                _EmployeeInfo.PlaceOfBirth = "";

                col = "DIACHI";
                _EmployeeInfo.Address = UnicodeConvert.TCVN3ToUnicode(dr[col].ToString().Trim());
                _EmployeeInfo.Phone = "";
                _EmployeeInfo.Nationality = 1;
                _EmployeeInfo.PassportNo = "";
                _EmployeeInfo.PassportIssueDate = DateTime.MinValue;
                _EmployeeInfo.PassportExpireDate = DateTime.MinValue;

                col = "SOCMND";
                _EmployeeInfo.IDCardNo = Convert.ToString(dr[col].ToString().Trim());

                col = "NGAYCMND";
                if (dr[col].ToString().Trim().Length > 0)
                    _EmployeeInfo.IDCardIssueDate = UISetting.GetDate(dr[col].ToString().Trim());

                col = "NOICAP";
                _EmployeeInfo.IDCardIssueAuthority = UnicodeConvert.TCVN3ToUnicode(dr[col].ToString().Trim());

                col = "SOBHXH";
                _EmployeeInfo.SIBookNo = Convert.ToString(dr[col].ToString().Trim());
                _EmployeeInfo.SIBookIssueDate = DateTime.MinValue;
                _EmployeeInfo.SIBookIssueAuthority = "";
                _EmployeeInfo.BankAccountNo = "";
                _EmployeeInfo.BankName = "";
                _EmployeeInfo.StartDate = DateTime.MinValue;
                _EmployeeInfo.EndDate = DateTime.MinValue;
                _EmployeeInfo.Description = "";
                _EmployeeInfo.IsOfficer = true;
                _EmployeeInfo.IsQuit = false;

                col = "SOKCB";
                _EmployeeInfo.MedicalNo = UnicodeConvert.TCVN3ToUnicode(dr[col].ToString().Trim());
                _EmployeeInfo.MedicalDate = DateTime.MinValue;

                col = "MA_BV";
                _EmployeeInfo.MedicalPlace = Convert.ToString(dr[col].ToString().Trim());

                _EmployeeInfo.Type = true;
                _EmployeeInfo.LeaveWorkID = 0;
                _EmployeeInfo.UnemployIns = false;
                _EmployeeInfo.UnemployInsDate = DateTime.MinValue;
                _EmployeeInfo.Specialist = "";
                _EmployeeInfo.Culture = "";
                _EmployeeInfo.IsInitial = true;
                _EmployeeInfo.PartyDate = DateTime.MinValue;
                _EmployeeInfo.ArmyFromDate = DateTime.MinValue;
                _EmployeeInfo.ArmyToDate = DateTime.MinValue;
                if (_wcfEmployee.Employee_CheckExist(0, _EmployeeInfo.Code, Program.intBranchID) == 0)
                {
                    if (_wcfEmployee.Employee_CheckExistSIBookNo(0, _EmployeeInfo.SIBookNo, Program.intBranchID) == 0)
                    {
                        _EmployeeID = _wcfEmployee.Employee_Insert(_EmployeeInfo);

                        //Insert muc luong:
                        col = "MAPB";
                        DataTable dtdept = _wcfDepartment.Department_GetByCode(Convert.ToString(dr[col]).Trim(), Program.strBranchCode).Tables[0];
                        if (dtdept.Rows.Count > 0)
                            departmentId = Convert.ToInt32(dtdept.Rows[0]["DEPARTMENT_ID"]);

                        _PDInfo = new PositionDetailInfo();
                        _PDInfo.DepartmentID = departmentId;
                        _PDInfo.EmployeeID = _EmployeeID;

                        col = "TUTHANG";
                        if (dr[col].ToString().Trim().Length > 0)
                            _PDInfo.BeginDate = UISetting.GetDate(dr[col].ToString().Trim());

                        _PDInfo.EndDate = DateTime.MinValue;
                        _PDInfo.IsActive = true;
                        _PDInfo.PositionID = positionId;
                        _PDInfo.PositionAllowance = 0;
                        _PDInfo.TotalSalary = 0;
                        _PDInfo.DateSalary = DateTime.MinValue;
                        _PDInfo.GradeID = gradeId;
                        _PDInfo.LevelID = 1;
                        _PDInfo.MinSalary = 0;

                        col = "ML";
                        decimal salary = 0;
                        if (dr[col].ToString().Trim().Length > 0)
                        {
                            salary = Convert.ToDecimal(dr[col].ToString().Trim());
                            if (salary > 100)
                            {
                                _PDInfo.BasicSalary = salary;
                                _PDInfo.BasicFactor = 0;
                                _PDInfo.PositionFactor = 0;
                                _PDInfo.OverFactor = 0;
                                _PDInfo.JobFactor = 0;
                                _PDInfo.AreaFactor = 0;
                            }
                            else
                            {
                                _PDInfo.BasicFactor = salary;
                                col = "PC1";
                                _PDInfo.PositionFactor = Convert.ToDecimal(dr[col].ToString());
                                col = "PC2";
                                _PDInfo.OverFactor = Convert.ToDecimal(dr[col].ToString());
                                col = "PC3";
                                _PDInfo.JobFactor = Convert.ToDecimal(dr[col].ToString());
                                col = "PC4";
                                _PDInfo.AreaFactor = Convert.ToDecimal(dr[col].ToString());
                            }
                        }
                        else
                        {
                            _PDInfo.BasicSalary = 0;
                            _PDInfo.BasicFactor = 0;
                            _PDInfo.PositionFactor = 0;
                            _PDInfo.OverFactor = 0;
                            _PDInfo.JobFactor = 0;
                            _PDInfo.AreaFactor = 0;
                        }
                        _PDInfo.PositionAllowance = 0;
                        _PDInfo.LunchAllowance = 0;
                        _PDInfo.TelephoneAllowance = 0;
                        _PDInfo.OtherFactor = 0;
                        _PDInfo.LaterInsurance = false;
                        _PDInfo.Job = "";
                        _PDInfo.DatePositionBegin = DateTime.MinValue;
                        _PDInfo.DatePositionEnd = DateTime.MinValue;
                        _PDInfo.Description = "";
                        _wcfPD.PositionDetail_Insert(_PDInfo);

                        //Insert bao hiem:
                        //_HeaderInfo = new HeaderInfo();
                        //_HeaderInfo.BranhCode = drHeader["madvi"].ToString().Trim();
                        //_HeaderInfo.Date = Convert.ToDateTime(drHeader["ngayct"].ToString().Substring(0, 10));
                        //_HeaderInfo.Month = Convert.ToInt32(drHeader["maqt"].ToString().Substring(4, 2));
                        //_HeaderInfo.Year = Convert.ToInt32(drHeader["maqt"].ToString().Substring(0, 4));
                        //_HeaderInfo.Period = Convert.ToInt32(drHeader["maqt"].ToString().Substring(6, 2));
                        //_HeaderInfo.Social = Convert.ToDecimal(drHeader["tyle_bhxh"]);
                        //_HeaderInfo.Medical = Convert.ToDecimal(drHeader["tyle_bhyt"]);
                        //_HeaderInfo.Unemployed = Convert.ToDecimal(drHeader["tyle_bhtn"]);
                        //_HeaderInfo.BasicSalary = Convert.ToDecimal(drHeader["mltt"]);
                        //_HeaderInfo.IsInitial = true;
                        //_HeaderInfo.Type = Convert.ToString(drHeader["loaidt"]);
                        //if (!_wcfHeader.Header_CheckExist(0, _HeaderInfo.BranhCode, _HeaderInfo.Date, _HeaderInfo.Month, _HeaderInfo.Year, _HeaderInfo.Period))
                        //{
                        //    _HeaderID = _wcfHeader.Header_Insert(_HeaderInfo);

                        //Insert bang HRM_Detail:
                        _DetailInfo = new DetailInfo
                                          {
                                              Detail_Documentid = _HeaderID,
                                              Detail_Insbookno = _EmployeeInfo.SIBookNo,
                                              Detail_Employeecode = _EmployeeInfo.Code,
                                              Detail_Fromdate = _PDInfo.BeginDate,
                                              Detail_Todate = _PDInfo.BeginDate
                                          };
                        col = "PA";
                        _DetailInfo.Detail_Instypecode = Convert.ToString(dr[col].ToString().Trim());
                        decimal decVal = 0;
                        col = "TYLE";
                        if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        {
                            if (decVal == Convert.ToDecimal("28.5"))
                            {
                                _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("4.5");
                                _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal("2");
                                _DetailInfo.Detail_Socialrate = Convert.ToDecimal("22");
                            }
                            else if (decVal == Convert.ToDecimal("26.5"))
                            {
                                _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("4.5");
                                _DetailInfo.Detail_Unemployedrate = 0;
                                _DetailInfo.Detail_Socialrate = Convert.ToDecimal("22");
                            }
                            else if (decVal == Convert.ToDecimal("25"))
                            {
                                _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("3");
                                _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal("2");
                                _DetailInfo.Detail_Socialrate = Convert.ToDecimal("20");
                            }
                            else if (decVal == Convert.ToDecimal("23"))
                            {
                                _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("3");
                                _DetailInfo.Detail_Unemployedrate = 0;
                                _DetailInfo.Detail_Socialrate = Convert.ToDecimal("20");
                            }
                            //else if (decVal == Convert.ToDecimal("4.5"))
                            //{
                            //    _DetailInfo.MedicalRate = Convert.ToDecimal("4.5");
                            //    _DetailInfo.UnemployedRate = 0;
                            //    _DetailInfo.SocialRate = 0;
                            //}
                            //else if (decVal == Convert.ToDecimal("3"))
                            //{
                            //    _DetailInfo.MedicalRate = Convert.ToDecimal("3");
                            //    _DetailInfo.UnemployedRate = 0;
                            //    _DetailInfo.SocialRate = 0;
                            //}
                            //else if (decVal == Convert.ToDecimal("2"))
                            //{
                            //    _DetailInfo.MedicalRate = 0;
                            //    _DetailInfo.UnemployedRate = Convert.ToDecimal("2");
                            //    _DetailInfo.SocialRate = 0;
                            //}
                        }
                        else
                        {
                            _DetailInfo.Detail_Medicalrate = 0;
                            _DetailInfo.Detail_Unemployedrate = 0;
                            _DetailInfo.Detail_Socialrate = 0;
                        }

                        _DetailInfo.Detail_Oldbasicfactor = 0;
                        _DetailInfo.Detail_Oldpositionfactor = 0;
                        _DetailInfo.Detail_Oldoverfactor = 0;
                        _DetailInfo.Detail_Oldjobfactor = 0;
                        _DetailInfo.Detail_Oldareafactor = 0;
                        if (salary > 100)
                        {
                            _DetailInfo.Detail_Newamount = salary;
                            _DetailInfo.Detail_Type = "ML";
                        }
                        else
                        {
                            _DetailInfo.Detail_Newbasicfactor = salary;
                            _DetailInfo.Detail_Type = "HS";
                        }
                        col = "PC1";
                        _DetailInfo.Detail_Newpositionfactor = Convert.ToDecimal(dr[col]);
                        col = "PC2";
                        _DetailInfo.Detail_Newoverfactor = Convert.ToDecimal(dr[col]);
                        col = "PC3";
                        _DetailInfo.Detail_Newjobfactor = Convert.ToDecimal(dr[col]);
                        col = "PC4";
                        _DetailInfo.Detail_Newareafactor = Convert.ToDecimal(dr[col]);
                        col = "MA_TINH";
                        _DetailInfo.Detail_Regioncode = Convert.ToString(dr[col].ToString().Trim());
                        col = "MA_BV";
                        _DetailInfo.Detail_Hospitalcode = dr[col].ToString().Trim();
                        _DetailInfo.Detail_Oldamount = 0;

                        _DetailInfo.Detail_Takecard = false;
                        _DetailInfo.Detail_Status = 3;
                        _DetailInfo.Detail_Totalmonth = 0;
                        if (!Detail_Controller.Instance().Detail_Exist(0, _DetailInfo.Detail_Insbookno, _DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate, _DetailInfo.Detail_Instypecode, _DetailInfo.Detail_Oldamount, _DetailInfo.Detail_Oldbasicfactor, _DetailInfo.Detail_Oldpositionfactor, _DetailInfo.Detail_Oldoverfactor, _DetailInfo.Detail_Oldjobfactor, _DetailInfo.Detail_Newamount, _DetailInfo.Detail_Newbasicfactor, _DetailInfo.Detail_Newpositionfactor, _DetailInfo.Detail_Newoverfactor, _DetailInfo.Detail_Newjobfactor))
                            _DetailID = Detail_Controller.Instance().Detail_Insert(_DetailInfo);
                        //}
                        //}
                    }
                }
            }
        }

        /*Util*/

        private bool ColumnEqual(object A, object B)
        {
            // Compares two values to see if they are equal. Also compares DBNULL.Value.
            // Note: If your DataTable contains object fields, then you must extend this
            // function to handle them in a meaningful way if you intend to group on them.
            if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
                return true;
            if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
                return false;
            return (A.Equals(B)); // value type standard comparison
        }

        public DataTable SelectDistinct(string tableName, DataTable sourceTable, string fieldName)
        {
            var dt = new DataTable(tableName);
            dt.Columns.Add(fieldName, sourceTable.Columns[fieldName].DataType);
            object lastValue = null;
            foreach (DataRow dr in sourceTable.Select("", fieldName))
            {
                if (lastValue == null || !(ColumnEqual(lastValue, dr[fieldName])))
                {
                    lastValue = dr[fieldName];
                    dt.Rows.Add(new object[] { lastValue });
                }
            }
            return dt;
        }

        /*---------------*/


        #region Sự kiện click trên menu chính
        //--------Menu click

        //------------------
        //1.Hệ thống
        private void mnuLogin_Click(object sender, EventArgs e)
        {
            isFirstLoad = true;
            Program.isAdmin = false;

            var f = new frmLogin();
            DialogResult fValue = f.ShowDialog(this);
            if (fValue == DialogResult.OK)
            {
                foreach (Form fChild in this.MdiChildren)
                {
                    fChild.Close();
                }
                mnuChangePass.Enabled =
                    mnuProfile.Enabled =
                    mnuMaskWork.Enabled =
                    mnuPayRoll.Enabled =
                    mnuList.Enabled =
                    mnuReport.Enabled =
                    mnuRecruitmentManagement.Enabled =
                    mnuInsurance.Enabled =
                    mnuExcuteSQL.Enabled = true;
                AuthenticUser();
                if (Program.strUserName.ToLower() == "phuhai")
                    mnuChangePass.Enabled = false;
            }
            mnuDonViQuanLy.Visible = (Program.isAdmin || Program.isChuyenQuan || (Program.strUserName.ToLower() == "vvtuy")) ? true : false;
            switch (Program.intInsType)
            {
                case 0:
                    mnuInsuranceFactor.Visible = true;
                    mnuInsuranceSalary.Visible = false;
                    break;
                case 1:
                    mnuInsuranceFactor.Visible = false;
                    mnuInsuranceSalary.Visible = true;
                    break;
                case 2:
                    mnuInsuranceFactor.Visible = true;
                    mnuInsuranceSalary.Visible = true;
                    break;
            }
        }

        private void mnuConfig_Click(object sender, EventArgs e)
        {
            var f = new frmConfig();
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                foreach (Form fChild in this.MdiChildren)
                {
                    fChild.Close();
                }
                mnuChangePass.Enabled =
                mnuProfile.Enabled =
                mnuMaskWork.Enabled =
                mnuPayRoll.Enabled =
                mnuList.Enabled =
                mnuReport.Enabled =
                mnuRecruitmentManagement.Enabled =
                mnuInsurance.Enabled =
                mnuExcuteSQL.Enabled = true;
                AuthenticUser();
            }
        }

        private void mnuUsers_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmUserList"))
            {
                var f = new frmUserList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuDonViQuanLy_Click(object sender, EventArgs e)
        {
            var f = new frmUserBranchList();
            DialogResult fValue = f.Show_Form();

            if (fValue == DialogResult.Cancel)
            {


                foreach (Form fChild in this.MdiChildren)
                {
                    fChild.Close();
                }
                tltBranch.Text = string.Format("{0} - {1}", Program.strBranchCode, Program.strBranch);
                tlbTotalEmp.Text = string.Format(" {0}", Program.TotalEmployee.ToString(CultureInfo.InvariantCulture));
                switch (Program.intInsType)
                {
                    case 0:
                        mnuInsuranceFactor.Visible = true;
                        mnuInsuranceSalary.Visible = false;
                        break;
                    case 1:
                        mnuInsuranceFactor.Visible = false;
                        mnuInsuranceSalary.Visible = true;
                        break;
                    case 2:
                        mnuInsuranceFactor.Visible = true;
                        mnuInsuranceSalary.Visible = true;
                        break;
                }
            }
        }

        private void mnuRoles_Click(object sender, EventArgs e)
        {
            var f = new frmRoles();
            f.Show();

        }

        private void mnuChangePass_Click(object sender, EventArgs e)
        {
            var f = new frmChangePassword();
            f.ShowDialog(this);
        }

        private void mnuImportData_Click(object sender, EventArgs e)
        {
            var f = new frmImportData();
            f.Show(this.dockPanelHRM);
            //return;
            if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
            {
                _Path = folderBrowserDialog1.SelectedPath;
                //_Path = openFileDialog1.FileName.Substring(0, openFileDialog1.FileName.LastIndexOf("\\"));
                _FolderName = Directory.GetFiles(_Path, "*.DBF");

                int count = 0;
                string tmp = "";
                string unc = "";

                count = _FolderName.Length;
                unc = _FolderName[count - 1].Substring(_FolderName[count - 1].LastIndexOf("\\", System.StringComparison.Ordinal) + 1);
                for (int i = 0; i < count - 1; i++)
                {
                    if (tmp.Length == 0)
                        tmp = _FolderName[i].Substring(_FolderName[i].LastIndexOf("\\", System.StringComparison.Ordinal) + 1);
                    else
                        tmp = tmp + "," + _FolderName[i].Substring(_FolderName[i].LastIndexOf("\\", System.StringComparison.Ordinal) + 1);
                }
                tmp = unc + "," + tmp;

                _FolderName = tmp.Split(',');

                var bgJ = new BackgroundWorker();

                bgJ.DoWork += new DoWorkEventHandler(bgJ_DoWork);

                bgJ.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgJ_RunWorkerCompleted);

                bgJ.RunWorkerAsync();

                fProgressbar = new frmProgressbar();
                fProgressbar.Show(this);
            }
        }

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new frmImportSMSThongBao();
            f.Show(this.dockPanelHRM);
        }

        private void tstrSMSTien_Click(object sender, EventArgs e)
        {
            var f = new frmImportSMSTien();
            f.Show(this.dockPanelHRM);
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //2.Danh mục
        private void mnuSystemParameter_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmParameter"))
            {
                var f = new frmParameter();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuBranch_Click(object sender, EventArgs e)
        {
            //if (!findMdiChildren("frmBranchList"))
            //{
            //    var f = new frmBranchList();
            //    f.Show(this.dockPanelHRM);
            //}
        }

        private void mnuDepartment_Click(object sender, EventArgs e)
        {
            //if (!findMdiChildren("frmDepartmentList"))
            //{
            //    var f = new frmDepartmentList();
            //    f.Show(this.dockPanelHRM);
            //}
        }

        private void mnuPosition_Click(object sender, EventArgs e)
        {
            //if (!findMdiChildren("frmPositionList"))
            //{
            //    var f = new frmPositionList();
            //    f.Show(this.dockPanelHRM);
            //}
        }

        private void mnuLevel_Click(object sender, EventArgs e)
        {
            //if (!findMdiChildren("frmLevelList"))
            //{
            //    var f = new frmLevelList();
            //    f.Show(this.dockPanelHRM);
            //}
        }

        private void mnuGrade_Click(object sender, EventArgs e)
        {
            //if (!findMdiChildren("frmGradeList"))
            //{
            //    var f = new frmGradeList();
            //    f.Show(this.dockPanelHRM);
            //}
        }

        private void mnuHesoMucLuong_Click(object sender, EventArgs e)
        {
            //if (!findMdiChildren("frmGradeDetailList"))
            //{
            //    var f = new frmGradeDetailList(false);
            //    f.Show(this.dockPanelHRM);
            //}
        }

        private void mnuContractType_Click(object sender, EventArgs e)
        {
            //if (!findMdiChildren("frmContractTypeList"))
            //{
            //    var f = new frmContractTypeList();
            //    f.Show(this.dockPanelHRM);
            //}
        }

        private void mnuLeave_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmLeaveList"))
            {
                var f = new frmLeaveList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuTypeOfLeaveWork_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmTypeOfLeaveWorkList"))
            {
                var f = new frmTypeOfLeaveWorkList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuLanguage_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmLanguagetList"))
            {
                var f = new frmLanguageList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuEthnic_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEthnicList"))
            {
                var f = new frmEthnicList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuReligion_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmReligionList"))
            {
                var f = new frmReligionList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuMaritalStatus_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmMaritalList"))
            {
                var f = new frmMaritalList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuStandard_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmStandardList"))
            {
                var f = new frmStandardList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuNational_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmNationalList"))
            {
                var f = new frmNationalList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuRegion_Click(object sender, EventArgs e)
        {

            if (!findMdiChildren("frmRegionList"))
            {
                var f = new frmRegionList(false);
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuHospital_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmHospitalList"))
            {
                var f = new frmHospitalList(false);
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuInsType_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmInsTypeList"))
            {
                var f = new frmInsTypeList(false);
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuRate_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmRateList"))
            {
                var f = new frmRateList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuBasicSalary_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmBasicSalaryList"))
            {
                var f = new frmBasicSalaryList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mtnTax_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmTaxList"))
            {
                var f = new frmTaxList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuFeastday_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmHolidayList"))
            {
                var f = new frmHolidayList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuInterestRate_Click(object sender, EventArgs e)
        {//Tiêu chí đánh giá
            if (!findMdiChildren("frmInterestRate"))
            {
                var f = new frmInterestRateList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuEvaluation_Click(object sender, EventArgs e)
        {//Lãi suất chậm nộp
            if (!findMdiChildren("frmEvaluationCriteriaList"))
            {
                var f = new frmEvaluationCriteriaList();
                f.Show(this.dockPanelHRM);
            }
        }

        //3.Nhân sự
        private void mnuEmployeeList_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEmployeeList"))
            {
                var f = new frmEmployeeList(false);
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuTangMoiNhanSu_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmNhanSu"))
            {
                var f = new frmNhanSu();
                //f.Show(this.dockPanelHRM);
                f.Show_Form();
            }
        }

        private void mnuLeaveWork_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmLeaveWorkList"))
            {
                var f = new frmLeaveWorkList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuEducation_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmEducationList"))
            {
                var f = new frmEducationList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuAward_Click(object sender, EventArgs e)
        {//Khen thưởng
            if (!findMdiChildren("frmAwardList"))
            {
                var f = new frmAwardList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuSafetyDevice_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmSafetyDeviceList"))
            {
                var f = new frmSafetyDeviceList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuDept_Click(object sender, EventArgs e)
        {
            var f = new frmChooseEmployeeList(UIParamater.Quyen_HoSoCanBo, false, false, true);
            f.Show(this.dockPanelHRM);
        }

        private void mnuBirthDay_Click(object sender, EventArgs e)
        {
            if (!findMdiChildren("frmBirthDayList"))
            {
                var f = new frmBirthDayList();
                f.Show(this.dockPanelHRM);
            }
        }
        private void mnuNoContract_Click(object sender, EventArgs e)
        {//DS chưa có đợp đồng
            if (!findMdiChildren("frmEmployeeNoLCList"))
            {
                var f = new frmEmployeeNoLCList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuNearExpireContract_Click(object sender, EventArgs e)
        {//DS sắp hết hạn hợp đồng
            if (!findMdiChildren("frmEmployeeLCNearInvalidList"))
            {
                var f = new frmEmployeeLCNearInvalidList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuExpireContract_Click(object sender, EventArgs e)
        {//DS hết hạn hợp đồng
            if (!findMdiChildren("frmEmployeeLCInvalidList"))
            {
                var f = new frmEmployeeLCInvalidList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuEmployeeNotComplete_Click(object sender, EventArgs e)
        {//DS hồ sơ chưa hoàn thiện
            if (!findMdiChildren("frmEmployeetmpList"))
            {
                var f = new frmEmployeetmpList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuFinishTenure_Click(object sender, EventArgs e)
        {//DS Sắp nghỉ hưu
            if (!findMdiChildren("frmSuperannuationList"))
            {
                var f = new frmSuperannuationList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuEmployeeNotActive_Click(object sender, EventArgs e)
        {//DS nhân viên đã nghỉ việc
            if (!findMdiChildren("frmEmployeeNotActiveList"))
            {
                var f = new frmEmployeeNotActiveList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuEvaluationEmployee_Click(object sender, EventArgs e)
        {//Đánh giá nhân viên
            if (!findMdiChildren("frmEvaluationList"))
            {
                var f = new frmEvaluationList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuImportEmployee_Click(object sender, EventArgs e)
        {//Import hồ sơ cán bộ
            openFileDialog1.Filter = "(*.xls)|*.xls";
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                //InputData(openFileDialog1.FileName);
            }
        }

        private void mnuScienceManagement_Click(object sender, EventArgs e)
        {//Đề tài khoa học
            if (!findMdiChildren("frmScienceManagementList"))
            {
                var f = new frmScienceManagementList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuIncreaseSalary_Click(object sender, EventArgs e)
        {//DS sắp nâng lương
            if (!findMdiChildren("frmIncreaseSalaryList"))
            {
                var f = new frmIncreaseSalaryList();
                f.Show(this.dockPanelHRM);
            }
        }


        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {//DS nghỉ thai sản
            if (!findMdiChildren("frmNghiThaiSanList"))
            {
                var frm = new frmNghiThaiSanList();
                frm.Show_Form();
            }
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {//DS thâm niên vượt khung

            if (!findMdiChildren("frmDanhSachVuotKhungList"))
            {
                var frm = new frmDanhSachVuotKhungList();
                frm.Show(this.dockPanelHRM);
            }
        }

        private void dSNghiThaiSanToolStripMenuItem_Click(object sender, EventArgs e)
        {//DS thâm niên nghề
            if (!findMdiChildren("frmDanhSachNgheList"))
            {
                var frm = new frmDanhSachNgheList();
                frm.Show(this.dockPanelHRM);
            }

        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
        }

        //4.Bảo hiểm
        private void mnuInsuranceFactor_Click(object sender, EventArgs e)
        {//Phát sinh bảo hiểm hệ số
            if (UIParamater.Quyen_PhatSinhBaoHiem._view)
            {
                var f = new frmFundList("HS");
                f.Show_Form();
            }
            else
                MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void mnuInsuranceSalary_Click(object sender, EventArgs e)
        {//Phát sinh bảo hiểm mức lương
            if (UIParamater.Quyen_PhatSinhBaoHiem._view)
            {
                var f = new frmFundList("ML");
                f.Show_Form();
            }
            else
                MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void mnuAmountFund_Click(object sender, EventArgs e)
        {//Quỹ lương bảo hiểm
            if (!findMdiChildren("frmFundList"))
            {
                //var f = new frmFundList();
                //f.Show(this.dockPanelHRM);
            }
        }

        private void mnuUNC_Click(object sender, EventArgs e)
        {//Ủy nhiệm chi
            if (!findMdiChildren("frmUNCList"))
            {
                var f = new frmUNCList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuInsPeriods_Click(object sender, EventArgs e)
        {//Quá trình đóng bảo hiểm
            if (!findMdiChildren("frmPremiumList"))
            {
                var f = new frmPremiumList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuFundSalary_Click(object sender, EventArgs e)
        {//Đối chiếu quỹ bảo hiểm
            if (!findMdiChildren("frmSalaryFundList"))
            {
                var f = new frmSalaryFundList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuLaterInsurance_Click(object sender, EventArgs e)
        {//Truy đóng bảo hiểm xh
            if (!findMdiChildren("frmLaterInsuranceList"))
            {
                var f = new frmLaterInsuranceList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuOffered_Click(object sender, EventArgs e)
        {
            var frm = new FrmOfferedList();
            frm.Show_Form();
        }

        private void mnuDeNghiCapSoBH_Click(object sender, EventArgs e)
        {//Đề nghị cấp sổ
            if (!findMdiChildren("frmIssueInsBookList"))
            {
                var f = new frmIssueInsBookList();
                f.Show(this.dockPanelHRM);
            }

        }

        private void mnuEditbook_Click(object sender, EventArgs e)
        {//Đổi số sổ BHXH
            if (!findMdiChildren("frmDoiSoList"))
            {
                var f = new frmDoiSoList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuMergebook_Click(object sender, EventArgs e)
        {//Gộp số sổ BHXH
            if (!findMdiChildren("frmMergeBookList"))
            {
                var f = new frmMergeBookList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mẫuÉpChứcDanhToolStripMenuItem_Click(object sender, EventArgs e)
        {//Danh sách quá trình chức danh
            if (!findMdiChildren("frmEmployee_QTChucDanh"))
            {
                var frm = new frmEmployee_QTChucDanh();
                frm.Show(this.dockPanelHRM);
            }

        }


        //5. Báo cáo----------------
        //---------------------------
        private void mnuCandidateReport_Click(object sender, EventArgs e)
        {/*
            if (UIParamater.Quyen_BaoCaoTuyenDung).View || UIParamater.Quyen_BaoCaoTuyenDung).Print)
            {
                frmCandidateReport f = new frmCandidateReport();
                if (f.ShowDialog() == DialogResult.OK)
                {
                    if (!findMdiChildren("frmPreviewReport", ""))
                    {
                        frmPreviewReport fReport = new frmPreviewReport("", new string[] { "" });
                        fReport.Show(this.dockPanelHRM);
                    }
                }
            }
            else
                MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
          */
        }

        private void đềNghịHưởngTrợCấpToolStripMenuItem_Click(object sender, EventArgs e)
        {//Đề nghị hưởng trợ cấp
            if (UIParamater.Quyen_BaoCaoHuongTroCap.View || UIParamater.Quyen_BaoCaoHuongTroCap.Print)
            {
                var f = new frmProposeReport();
                if (f.ShowDialog() == DialogResult.OK)
                {
                    //if (!findMdiChildren("frmPreviewReport", UpdateUI.GetString(f.ReportText)))
                    //{
                    var fReport = new frmPreviewReport(f.ReportType, new string[] { f.Month, f.Year, f.ReportText });
                    fReport.Show(this.dockPanelHRM);
                    //}
                }
            }
            else
                MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        //------------6.Trợ giúp
        //----------------------

        private void aboutHRMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Giới thiệu
            var f = new frmAbout();
            f.Show();
        }

        private void mnuUserGuide_Click(object sender, EventArgs e)
        {
            //Hướng dẫn sử dụng
            try
            {
                Help.ShowHelp(this, helpProvider1.HelpNamespace);
            }
            catch (Exception ex)
            {
                FormGlobals.Message_Error(ex);
            }
        }

        private void mnuVersionUpdate_Click(object sender, EventArgs e)
        {
            //Cập nhật phần mềm
            if (HasNewVerion())
                UpdateNewVersion();
            else
                if (FormGlobals.Message_Confirm("Không có bản cập nhật mới hơn. Bạn có chắc vẫn muốn cập nhật?"))
                    UpdateNewVersion();
        }

        private void mnuExcuteSQL_Click(object sender, EventArgs e)
        {
            //Truy vấn
            if (findMdiChildren("frmTool")) return;
            var f = new frmTool();
            f.Show(this.dockPanelHRM);
        }

        private void mnuTeamviewer_Click(object sender, EventArgs e)
        {
            //Hỗ trợ từ xa
            Process.Start(Application.StartupPath + "\\TeamViewerQS.exe");
        }

        private void thưViệnMẫuTờKhaiBáoCáoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Thư viện mẫu báo cáo
            const string urlSite = "http://www.mediafire.com/?lf1l7sbhu551m";
            try
            {
                var sInfo = new ProcessStartInfo(urlSite);
                Process.Start(sInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(HrmResources.YOUR_COMPUTER_MUST_HAVE_A_WEB_BROWSER);
            }
        }

        //-------7. Chấm công
        //----------------
        private void mnuLoadCheckTime_Click(object sender, EventArgs e)
        {//Nạp dữ liệu chấm công
            var opd = new OpenFileDialog { Filter = HrmResources.FILTER_DAT_FILE };
            if (opd.ShowDialog() == DialogResult.OK)
            {
                string strFilePath = opd.FileName;
                PopulateDataTableFromUploadedFile(strFilePath);
                OpenSplash();
            }
        }

        private void mnuEmployeeShift_Click(object sender, EventArgs e)
        {//Bảng phân ca
            if (!findMdiChildren("frmEmployeeShiftList"))
            {
                var f = new frmEmployeeShiftList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuMaskWorkTable_Click(object sender, EventArgs e)
        {//Bảng chấm công
            if (!findMdiChildren("frmMarkWork"))
            {
                var f = new frmMarkWork();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuViewAttend_Click(object sender, EventArgs e)
        {//Bảng theo dõi sổ công
            if (!findMdiChildren("frmMarkWorkDetail"))
            {
                var f = new frmMarkWorkDetail();
                f.Show(this.dockPanelHRM);
            }

        }


        //7. Tiền lương
        //-----------------
        private void mnuSalary_Click(object sender, EventArgs e)
        {//Bảng lương
            if (!findMdiChildren("frmSalary"))
            {
                var f = new frmSalaryList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuAdvancePayment_Click(object sender, EventArgs e)
        {//Tạm ứng lương
            if (!findMdiChildren("frmAdvancePaymentList"))
            {
                var f = new frmAdvancePaymentList();
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuServiceCharge_Click(object sender, EventArgs e)
        {//Phí dịch vụ
            if (!findMdiChildren("frmServiceChargeList"))
            {
                var f = new frmServiceChargeList();
                f.Show(this.dockPanelHRM);
            }
        }


        //--8. Tuyển dụng
        private void mnuCandidateList_Click(object sender, EventArgs e)
        {//Ứng viên
            if (!findMdiChildren("frmCandidateList"))
            {
                var f = new frmCandidateList(false);
                f.Show(this.dockPanelHRM);
            }
        }

        private void mnuRecruitment_Click(object sender, EventArgs e)
        {//Đợt tuyển dụng
            if (!findMdiChildren("frmCRList"))
            {
                var f = new frmCRList();
                f.Show(this.dockPanelHRM);
            }
        }


        #endregion

        private void épSốThẻBHYTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frm = new frmEpSoTheBHYT();
            frm.Show_Form();
        }

        //private void dSKhôngCònĐóngToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    frmDSKhongThamGiaBH frm = new frmDSKhongThamGiaBH();
        //    frm.Show_Form();
        //}

        private void đềNghịChôtSổToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frm = new frmChotSo();
            frm.Show_Form();
        }

        private void MnuDeNghiTraTheClick(object sender, EventArgs e)
        {
            var frm = new FrmReturnInsBookList();
            frm.Show_Form();
        }

        //

        private void hồSơTăngMớiD02TSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //frmPreviewReport f = new frmPreviewReport("BHXHMauD02TS_Moi", new string[] { "Mẫu D02-TS", "0", "", "", "","1" });
            //if (!f.isExport)
            //    f.Show(this);
        }

        private void tăngMớiD02TSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sMaD02TS = "10103N";
            D02TS_Online(sMaD02TS);
        }

        private void giảmD02TSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sMaD02TS = "10106N";
            D02TS_Online(sMaD02TS);
        }

        private void D02TS_Online(string sMaD02TS)
        {
            bool isTangMoi = (sMaD02TS == "10103N");
            //
            string tongSoToKhai = "", tongSoSoBHHXDeNghiCap = "", tongSoTheBHYTDeNghiCap = "", thoiHan = "", _period = "", _month = "", _year = "", isExportExcel = "1";
            frmReportParameterSum f = new frmReportParameterSum(_period, _month, _year, isExportExcel == "1");

            string templateFile = "";
            DataSet ds = new DataSet();
            Dictionary<string, object> dicParameters = new Dictionary<string, object>();

            string sXLSFilePath = "";
            if (f.Show_Form(isExportExcel == "1" ? 1 : 0) == DialogResult.OK)//report
            {
                string sFilePath = Util.CreateFolderTemplate();

                //Chọn chỗ lưu file xls
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "(*.xls)|*.xls";
                sfd.InitialDirectory = sFilePath != "" ? sFilePath : Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                sfd.FileName = "D02-TS_" + sMaD02TS + "_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hhMMssfff") + ".xls";
                if (sfd.ShowDialog(this) == DialogResult.OK)
                {
                    sXLSFilePath = sfd.FileName;
                }
                else
                    return;

                //-------------------------------------
                FormGlobals.App_ProgressShow(delegate()
                {

                    tongSoToKhai = f.TongSoToKhai;
                    tongSoSoBHHXDeNghiCap = f.TongSoSoBHHXDeNghiCap;
                    tongSoTheBHYTDeNghiCap = f.TongSoTheBHYTDeNghiCap;
                    thoiHan = f.ThoiHan;
                    //isExport = f.isExportExcel;

                    if (isExportExcel == "1")
                    {
                        _period = f.period;
                        _month = f.month;
                        _year = f.year;
                    }

                    if (thoiHan.Length == 0)
                        thoiHan = "Thời hạn từ .../.../...... đến .../.../......";

                    ////Tăng mới xuất mẫu D02_TS_TangMoi nguoc lai xuat mẫu giảm
                    if (isTangMoi)
                        templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\D02-TS_TangMoi.xls");
                    else
                        templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\D02-TS_Giam.xls");
                    //
                    BranchClient wcfBranch = Service.Branch();
                    BranchInfo branchInfo = wcfBranch.Branch_GetInfo(Program.intBranchID);

                    dicParameters.Add("Month", _month);
                    dicParameters.Add("Year", _year);
                    dicParameters.Add("TongSoToKhai", tongSoToKhai);
                    dicParameters.Add("TongSoSoBHHXDeNghiCap", tongSoSoBHHXDeNghiCap);
                    dicParameters.Add("TongSoTheBHYTDeNghiCap", tongSoTheBHYTDeNghiCap);
                    dicParameters.Add("ThoiHan", thoiHan);

                    dicParameters.Add("BranchName", Program.strBranch);
                    dicParameters.Add("RepName", Program.strBranchRepName);
                    dicParameters.Add("BranchCode", Program.strBranchBHXH);
                    dicParameters.Add("BranchAddress", Program.strBranchAddress);
                    dicParameters.Add("Branch_ScheduledMan", branchInfo.Branch_ScheduledMan);
                    dicParameters.Add("Branch_BHXHOfficers", branchInfo.Branch_BHXHOfficers);
                    dicParameters.Add("Branch_RepName", branchInfo.RepName);
                    dicParameters.Add("Branch_BHXHBossofDistrict", branchInfo.Branch_BHXHBossofDistrict);
                    dicParameters.Add("Ngay", DateTime.Now.Day);
                    dicParameters.Add("Thang", DateTime.Now.Month);
                    dicParameters.Add("Nam", DateTime.Now.Year);
                    //

                    DetailClient wcfDetail = Service.Detail();
                    //SalaryClient wcfSalary = Service.Salary();

                    //1.1 Lao động tăng
                    int iPeriod = 0, iMonth = 0, iYear = 0;
                    Int32.TryParse(_period, out iPeriod);
                    Int32.TryParse(_month, out iMonth);
                    Int32.TryParse(_year, out iYear);
                    string _typeCode = "";
                    //
                    //-----------------------Lấy dữ liệu, giống xuất mẫu D02-TS report
                    //1.1 Lao động tăng
                    DataTable dt11TangLaoDong = wcfDetail.Detail_Mau03_TangMoi_TEST(iPeriod, iMonth, iYear, Program.strBranchBHXH, _typeCode).Tables[0].Copy();
                    dt11TangLaoDong.TableName = "tblTangLaoDong";

                    DataColumn col = new DataColumn("TienLuong");
                    col.DataType = typeof(decimal);
                    col.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt11TangLaoDong.Columns.Add(col);

                    AddAutoIncrementColumn(dt11TangLaoDong);

                    //--Lấy danh sách điều chỉnh lương
                    DataTable dtDieuChinh = wcfDetail.Detail_Mau03DCLuong_TEST(iPeriod, iMonth, iYear, Program.strBranchBHXH, _typeCode).Tables[0];

                    //--Lấy danh sách bổ sung bảo hiểm tn
                    DataTable dtBoSungBHTN = wcfDetail.Detail_Mau03BoSungBHTN(iPeriod, iMonth, iYear, Program.strBranchCode).Tables[0];


                    //1.2 Tăng mức đóng
                    string queryTang = "Detail_OldBasicFactor + Detail_OldAmount + Detail_OldPositionFactor +  Detail_OldOverFactor + Detail_OldJobFactor < Detail_NewBasicFactor + Detail_NewAmount + Detail_NewPositionFactor +  Detail_NewOverFactor + Detail_NewJobFactor";
                    DataView dv12TangMucDong = new DataView(dtDieuChinh, queryTang, "", DataViewRowState.CurrentRows);
                    DataTable dt12TangMucDong = dv12TangMucDong.ToTable();
                    dt12TangMucDong.TableName = "tblTangMucDong";

                    DataColumn col1 = new DataColumn("TienLuong");
                    col1.DataType = typeof(Decimal);
                    col1.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt12TangMucDong.Columns.Add(col1);

                    AddAutoIncrementColumn(dt12TangMucDong);

                    //--Lấy danh sách lao động giảm: có cả TT, TU, giảm mức đóng
                    DataTable dtGiam = wcfDetail.Detail_Mau03Giam_TEST(iPeriod, iMonth, iYear, Program.strBranchBHXH, _typeCode).Tables[0];

                    //2.1 Lao động giảm
                    string queryGiamLaoDong = "Detail_InsTypeCode <> 'TT' AND Detail_InsTypeCode <> 'TU' ";
                    DataView dv12GiamLaoDong = new DataView(dtGiam, queryGiamLaoDong, "", DataViewRowState.CurrentRows);
                    DataTable dt21GiamLaoDong = dv12GiamLaoDong.ToTable();
                    dt21GiamLaoDong.TableName = "tblGiamLaoDong";

                    DataColumn col2 = new DataColumn("TienLuong");
                    col2.DataType = typeof(decimal);
                    col2.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt21GiamLaoDong.Columns.Add(col2);

                    AddAutoIncrementColumn(dt21GiamLaoDong);

                    //2.2 Giảm mức đóng
                    string queryGiam = "Detail_OldBasicFactor + Detail_OldAmount + Detail_OldPositionFactor +  Detail_OldOverFactor + Detail_OldJobFactor >= Detail_NewBasicFactor + Detail_NewAmount + Detail_NewPositionFactor +  Detail_NewOverFactor + Detail_NewJobFactor";
                    DataView dv22GiamMucDong = new DataView(dtDieuChinh, queryGiam, "", DataViewRowState.CurrentRows);
                    DataTable dt22GiamMucDong = dv22GiamMucDong.ToTable();
                    dt22GiamMucDong.TableName = "tblGiamMucDong";

                    DataColumn col3 = new DataColumn("TienLuong");
                    col3.DataType = typeof(decimal);
                    col3.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt22GiamMucDong.Columns.Add(col3);

                    AddAutoIncrementColumn(dt22GiamMucDong);

                    //1.3 Tăng bổ sung BHYT (TT)
                    string queryTT = "Detail_InsTypeCode = 'TT' ";
                    DataView dv13BoSungTangBHYT = new DataView(dtGiam, queryTT, "", DataViewRowState.CurrentRows);
                    DataTable dt13BoSungTangBHYT = dv13BoSungTangBHYT.ToTable();
                    dt13BoSungTangBHYT.TableName = "tblTangBHYT";


                    DataColumn col4 = new DataColumn("TienLuong");
                    col4.DataType = typeof(decimal);
                    col4.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt13BoSungTangBHYT.Columns.Add(col4);

                    AddAutoIncrementColumn(dt13BoSungTangBHYT);

                    //2.3 Giảm bổ sung BHYT (TT)
                    string queryTU = "Detail_InsTypeCode = 'TU' ";
                    DataView dv23BoSungGiamBHYT = new DataView(dtGiam, queryTU, "", DataViewRowState.CurrentRows);
                    DataTable dt23BoSungGiamBHYT = dv23BoSungGiamBHYT.ToTable();
                    dt23BoSungGiamBHYT.TableName = "tblGiamBHYT";


                    DataColumn col6 = new DataColumn("TienLuong");
                    col6.DataType = typeof(decimal);
                    col6.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt23BoSungGiamBHYT.Columns.Add(col6);

                    AddAutoIncrementColumn(dt23BoSungGiamBHYT);

                    ////3.1 Tăng bổ sung BHTN
                    string queryBSTN_Tang = " Detail_InsTypeCode IN ('DN','TN') ";
                    DataView dv31BoSungBHTN_Tang = new DataView(dtBoSungBHTN, queryBSTN_Tang, "", DataViewRowState.CurrentRows);
                    DataTable dt31BoSungBHTN_Tang = dv31BoSungBHTN_Tang.ToTable();
                    dt31BoSungBHTN_Tang.TableName = "tblTangBHTN";


                    DataColumn col7 = new DataColumn("TienLuong");
                    col7.DataType = typeof(decimal);
                    col7.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt31BoSungBHTN_Tang.Columns.Add(col7);

                    AddAutoIncrementColumn(dt31BoSungBHTN_Tang);

                    //Giảm
                    string queryBSTN_Giam = " Detail_InsTypeCode IN ('GN') ";
                    DataView dv31BoSungBHTN_Giam = new DataView(dtBoSungBHTN, queryBSTN_Giam, "", DataViewRowState.CurrentRows);
                    DataTable dt31BoSungBHTN_Giam = dv31BoSungBHTN_Giam.ToTable();
                    dt31BoSungBHTN_Giam.TableName = "tblGiamBHTN";


                    DataColumn col8 = new DataColumn("TienLuong");
                    col8.DataType = typeof(decimal);
                    col8.Expression = "IIF(Detail_NewBasicFactor=0,IIF(Detail_NewAmount=0,0,Detail_NewAmount),Detail_NewBasicFactor)";
                    dt31BoSungBHTN_Giam.Columns.Add(col8);

                    AddAutoIncrementColumn(dt31BoSungBHTN_Giam);

                    //
                    DataTable dtCongTang = dt11TangLaoDong.Clone();

                    Decimal TongTiengLuongCuHS = 0,
                        TongHeSoCuHS = 0,
                        TongChucVuCuHS = 0,
                        TongTNVKCuHS = 0,
                        TongTNNGCuHS = 0,
                        TongTienLuongMoiHS = 0,
                        TongHeSoMoiHS = 0,
                        TongChucVuMoiHS = 0,
                        TongTNVKMoiHS = 0,
                        TongTNNGMoiHS = 0;

                    Decimal TongTiengLuongCuML = 0,
                        TongHeSoCuML = 0,
                        TongChucVuCuML = 0,
                        TongTNVKCuML = 0,
                        TongTNNGCuML = 0,
                        TongTienLuongMoiML = 0,
                        TongHeSoMoiML = 0,
                        TongChucVuMoiML = 0,
                        TongTNVKMoiML = 0,
                        TongTNNGMoiML = 0;

                    DataTable[] dtArray = null;
                    if (isTangMoi)
                    {
                        dtArray = new DataTable[] {
                        dt11TangLaoDong, 
                        //dt12TangMucDong,
                        //dt13BoSungTangBHYT,
                        //dt31BoSungBHTN_Tang
                        };
                    }
                    else
                    {
                        dtArray = new DataTable[] {
                        //dt11TangLaoDong, 
                        dt12TangMucDong,
                        dt13BoSungTangBHYT,
                        dt31BoSungBHTN_Tang
                        };
                    }


                    foreach (DataTable dt in dtArray)
                    {
                        TongTiengLuongCuHS = Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldAmount)", "Detail_Type='HS'"), 0);
                        TongHeSoCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldBasicFactor)", "Detail_Type='HS'"), 0);
                        TongChucVuCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldPositionFactor)", "Detail_Type='HS'"), 0);
                        TongTNVKCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldoverfactor_Percent)", "Detail_Type='HS'"), 0);
                        TongTNNGCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldjobfactor_Percent)", "Detail_Type='HS'"), 0);
                        TongTienLuongMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewAmount)", "Detail_Type='HS'"), 0);
                        TongHeSoMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewBasicFactor)", "Detail_Type='HS'"), 0);
                        TongChucVuMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewPositionFactor)", "Detail_Type='HS'"), 0);
                        TongTNVKMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newoverfactor_Percent)", "Detail_Type='HS'"), 0);
                        TongTNNGMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newjobfactor_Percent)", "Detail_Type='HS'"), 0);
                        //
                        TongTiengLuongCuML = Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldAmount)", "Detail_Type='ML'"), 0);
                        TongHeSoCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldBasicFactor)", "Detail_Type='ML'"), 0);
                        TongChucVuCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldPositionFactor)", "Detail_Type='ML'"), 0);
                        TongTNVKCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldoverfactor_Percent)", "Detail_Type='ML'"), 0);
                        TongTNNGCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldjobfactor_Percent)", "Detail_Type='ML'"), 0);
                        TongTienLuongMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewAmount)", "Detail_Type='ML'"), 0);
                        TongHeSoMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewBasicFactor)", "Detail_Type='ML'"), 0);
                        TongChucVuMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewPositionFactor)", "Detail_Type='ML'"), 0);
                        TongTNVKMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newoverfactor_Percent)", "Detail_Type='ML'"), 0);
                        TongTNNGMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newjobfactor_Percent)", "Detail_Type='ML'"), 0);
                    }

                    //DataRow drTongTang = dtCongTang.NewRow();
                    //drTongTang["Detail_OldAmount"] = TongTiengLuongCuHS;
                    //drTongTang["Detail_OldBasicFactor"] = TongHeSoCuHS;
                    //drTongTang["Detail_OldPositionFactor"] = TongChucVuCuHS;
                    //drTongTang["Detail_Oldoverfactor_Percent"] = TongTNVKCuHS;
                    //drTongTang["Detail_Oldjobfactor_Percent"] = TongTNNGCuHS;
                    //drTongTang["Detail_NewAmount"] = TongTienLuongMoiHS;
                    //drTongTang["Detail_NewBasicFactor"] = TongHeSoMoiHS;
                    //drTongTang["Detail_NewPositionFactor"] = TongChucVuMoiHS;
                    //drTongTang["Detail_Newoverfactor_Percent"] = TongTNVKMoiHS;
                    //drTongTang["Detail_Newjobfactor_Percent"] = TongTNNGMoiHS;
                    //dtCongTang.Rows.Add(drTongTang);
                    ////Add DataSource -> Report
                    //dtCongTang.TableName = "tblCongTang";

                    //
                    if (TongTienLuongMoiML > 0 && TongHeSoMoiHS > 0)
                        dicParameters.Add("TongTangTienLuong", "ML: " + TongTienLuongMoiML.ToString("#,##0") + " - HS: " + TongHeSoMoiHS.ToString("#,##0.00"));
                    else
                        dicParameters.Add("TongTangTienLuong", TongTienLuongMoiML > 0 ? TongTienLuongMoiML.ToString("#,##0") : (TongHeSoMoiHS > 0 ? TongHeSoMoiHS.ToString("#,##0.00") : ""));
                    dicParameters.Add("TongTangCV", TongChucVuMoiHS);
                    dicParameters.Add("TongTangTNVK", TongTNVKMoiHS);
                    dicParameters.Add("TongTangTNN", TongTNNGMoiHS);


                    DataTable dtCongGiam = dtCongTang.Clone();
                    TongTiengLuongCuHS = 0;
                    TongHeSoCuHS = 0;
                    TongChucVuCuHS = 0;
                    TongTNVKCuHS = 0;
                    TongTNNGCuHS = 0;
                    TongTienLuongMoiHS = 0;
                    TongHeSoMoiHS = 0;
                    TongChucVuMoiHS = 0;
                    TongTNVKMoiHS = 0;
                    TongTNNGMoiHS = 0;
                    //
                    TongTiengLuongCuML = 0;
                    TongHeSoCuML = 0;
                    TongChucVuCuML = 0;
                    TongTNVKCuML = 0;
                    TongTNNGCuML = 0;
                    TongTienLuongMoiML = 0;
                    TongHeSoMoiML = 0;
                    TongChucVuMoiML = 0;
                    TongTNVKMoiML = 0;
                    TongTNNGMoiML = 0;
                    //

                    dtArray = new DataTable[] {
                        dt21GiamLaoDong, 
                        dt22GiamMucDong,
                        dt31BoSungBHTN_Giam,
                        dt31BoSungBHTN_Giam
                    };

                    foreach (DataTable dt in dtArray)
                    {
                        TongTiengLuongCuHS = Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldAmount)", "Detail_Type='HS'"), 0);
                        TongHeSoCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldBasicFactor)", "Detail_Type='HS'"), 0);
                        TongChucVuCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldPositionFactor)", "Detail_Type='HS'"), 0);
                        TongTNVKCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldoverfactor_Percent)", "Detail_Type='HS'"), 0);
                        TongTNNGCuHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldjobfactor_Percent)", "Detail_Type='HS'"), 0);
                        TongTienLuongMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewAmount)", "Detail_Type='HS'"), 0);
                        TongHeSoMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewBasicFactor)", "Detail_Type='HS'"), 0);
                        TongChucVuMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewPositionFactor)", "Detail_Type='HS'"), 0);
                        TongTNVKMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newoverfactor_Percent)", "Detail_Type='HS'"), 0);
                        TongTNNGMoiHS += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newjobfactor_Percent)", "Detail_Type='HS'"), 0);
                        //
                        TongTiengLuongCuML = Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldAmount)", "Detail_Type='ML'"), 0);
                        TongHeSoCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldBasicFactor)", "Detail_Type='ML'"), 0);
                        TongChucVuCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_OldPositionFactor)", "Detail_Type='ML'"), 0);
                        TongTNVKCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldoverfactor_Percent)", "Detail_Type='ML'"), 0);
                        TongTNNGCuML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Oldjobfactor_Percent)", "Detail_Type='ML'"), 0);
                        TongTienLuongMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewAmount)", "Detail_Type='ML'"), 0);
                        TongHeSoMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewBasicFactor)", "Detail_Type='ML'"), 0);
                        TongChucVuMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_NewPositionFactor)", "Detail_Type='ML'"), 0);
                        TongTNVKMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newoverfactor_Percent)", "Detail_Type='ML'"), 0);
                        TongTNNGMoiML += Globals.DB_GetValue<decimal>(dt.Compute("SUM(Detail_Newjobfactor_Percent)", "Detail_Type='ML'"), 0);
                    }


                    //DataRow drCongGiam = dtCongGiam.NewRow();
                    //drCongGiam["Detail_OldAmount"] = TongTiengLuongCu;
                    //drCongGiam["Detail_OldBasicFactor"] = TongHeSoCu;
                    //drCongGiam["Detail_OldPositionFactor"] = TongChucVuCu;
                    //drCongGiam["Detail_Oldoverfactor_Percent"] = TongTNVKCu;
                    //drCongGiam["Detail_Oldjobfactor_Percent"] = TongTNNGCu;

                    //drCongGiam["Detail_NewAmount"] = TongTienLuongMoi;
                    //drCongGiam["Detail_NewBasicFactor"] = TongHeSoMoi;
                    //drCongGiam["Detail_NewPositionFactor"] = TongChucVuMoi;
                    //drCongGiam["Detail_Newoverfactor_Percent"] = TongTNVKMoi;
                    //drCongGiam["Detail_Newjobfactor_Percent"] = TongTNNGMoi;
                    //dtCongGiam.Rows.Add(drCongGiam);
                    ////Add DataSource -> Report

                    //dtCongGiam.TableName = "tblCongGiam";

                    //
                    if (TongTienLuongMoiML > 0 && TongHeSoMoiHS > 0)
                        dicParameters.Add("TongGiamTienLuong", "ML: " + TongTienLuongMoiML.ToString("#,##0") + " - HS: " + TongHeSoMoiHS.ToString("#,##0.00"));
                    else
                        dicParameters.Add("TongGiamTienLuong", TongTienLuongMoiML > 0 ? TongTienLuongMoiML.ToString("#,##0") : (TongHeSoMoiHS > 0 ? TongHeSoMoiHS.ToString("#,##0.00") : ""));

                    dicParameters.Add("TongGiamCV", TongChucVuMoiHS);
                    dicParameters.Add("TongGiamTNVK", TongTNVKMoiHS);
                    dicParameters.Add("TongGiamTNN", TongTNNGMoiHS);



                    //------------------------------------------------------------------------------------------------------------------------
                    //Sheet import sms
                    //DetailClient _wcfDetail = Service.Detail();
                    //DataTable dtImport = _wcfDetail.Detail_Mau02_Excel(iPeriod, iMonth, iYear, Program.strBranchBHXH, false).Tables[0].Copy();
                    DataTable dtImport = Detail_Controller.Instance().Get4D02TSImportSMS(iPeriod, iMonth, iYear, Program.strBranchBHXH).Copy();

                    dtImport.TableName = "tblImport";
                    dtImport.Columns.Remove("STT");
                    AddAutoIncrementColumn(dtImport);

                    //Them cot TjnhLaj, danh dau x het, hjepdh: 08/09/2012
                    TinhLaiBaoHiem("Mau02a", iMonth, iYear, ref dtImport);
                    for (int j = 0; j < dtImport.Rows.Count; j++)
                    {
                        //Liệt kê các cột theo thứ tự côt của bảng gốc, kết hợp gán dữ liệu dòng tương ứng cột
                        for (int k = 0; k < dtImport.Columns.Count; k++)
                        {
                            if (dtImport.Columns[k].DataType == typeof(String))
                                dtImport.Rows[j][k] = UnicodeConvert.UnicodeToTCVN3(dtImport.Rows[j][k].ToString());
                        }
                    }
                    //
                    ds.Tables.AddRange(new DataTable[] { 
                    dt11TangLaoDong,
                    dt12TangMucDong,
                    dt13BoSungTangBHYT,
                    dt21GiamLaoDong,
                    dt22GiamMucDong,
                    dt23BoSungGiamBHYT,
                    dt31BoSungBHTN_Giam,
                    dt31BoSungBHTN_Tang,
                    //dtCongTang,
                    //dtCongGiam,
                    dtImport
                });
                }, "Đang lấy dữ liệu");
                //
                //string sFilePath = "";

                FormGlobals.App_ProgressShow(delegate()
                {
                    sFilePath = ExcelHelper.Excel_ExportWithTemplate(ds, templateFile, dicParameters, sXLSFilePath);
                }, "Xuất dữ liệu ra excel");

                Process.Start(sFilePath);
            }
            else
            {
                return;
            }
        }

        private void TinhLaiBaoHiem(string Loai, int MonthVal, int YearVal, ref DataTable dt)
        {
            dt.Columns.Add("TinhLai");
            bool TinhLai = false;
            string PATinhLai = "AD/ON/DC/TC/TD/TM/TN";

            foreach (DataRow dr in dt.Rows)
            {
                TinhLai = false;
                //
                switch (Loai)
                {
                    case "Mau03a":
                        string PA = dr["Detail_InsTypeCode"].ToString();
                        string ToDate = dr["Detail_FromDate"].ToString();
                        int DenThang = Convert.ToInt32(ToDate.Split(new char[] { '/' })[0]);
                        int DenNam = Convert.ToInt32(ToDate.Split(new char[] { '/' })[1]);
                        decimal TongMucCu = (decimal)dr["OldAmount"] + (decimal)dr["Detail_OldPositionFactor"] + (decimal)dr["Detail_OldOverFactor"] + (decimal)dr["Detail_OldJobFactor"] + (decimal)dr["Detail_OldAreaFactor"];
                        decimal TongMucMoi = (decimal)dr["NewAmount"] + (decimal)dr["Detail_NewPositionFactor"] + (decimal)dr["Detail_NewOverFactor"] + (decimal)dr["Detail_NewJobFactor"] + (decimal)dr["Detail_NewAreaFactor"];
                        int SoThang = (YearVal - DenNam) * 12 + (MonthVal - DenThang);
                        //
                        //TinhLai = PATinhLai.Contains(PA) && SoThang > 1 && TongMucMoi > TongMucCu;
                        TinhLai = PATinhLai.Contains(PA) && SoThang > 1; //6/5: Truy giảm cũng tính lãi
                        break;
                    case "Mau02a":
                        PA = dr["Detail_InsTypeCode"].ToString();
                        ToDate = dr["Detail_FromDate"].ToString();
                        DenThang = Convert.ToInt32(ToDate.Split(new char[] { '/' })[0]);
                        DenNam = Convert.ToInt32(ToDate.Split(new char[] { '/' })[1]);
                        //TongMucCu = (decimal)dr["OldAmount"] + (decimal)dr["Detail_OldPositionFactor"] + (decimal)dr["Detail_OldOverFactor"] + (decimal)dr["Detail_OldJobFactor"] + (decimal)dr["Detail_OldAreaFactor"];
                        TongMucCu = (Decimal)dr["Tongmuccu"];
                        //TongMucMoi = (decimal)dr["NewAmount"] + (decimal)dr["Detail_NewPositionFactor"] + (decimal)dr["Detail_NewOverFactor"] + (decimal)dr["Detail_NewJobFactor"] + (decimal)dr["Detail_NewAreaFactor"];
                        TongMucMoi = (Decimal)dr["Tongmucmoi"];
                        SoThang = (YearVal - DenNam) * 12 + (MonthVal - DenThang);
                        //
                        //TinhLai = PATinhLai.Contains(PA) && SoThang > 1 && TongMucMoi > TongMucCu;
                        TinhLai = PATinhLai.Contains(PA) && SoThang > 1; //6/5: Truy giảm cũng tính lãi
                        break;
                }
                //
                if (TinhLai)
                    dr["TinhLai"] = "X";
            }
        }

        public void AddAutoIncrementColumn(DataTable dt)
        {
            if (dt.Columns.Contains("STT"))
            {
                dt.Columns.Remove("STT");
                dt.AcceptChanges();
            }
            if (!dt.Columns.Contains("STT"))
            {
                DataColumn column = new DataColumn("STT");
                column.DataType = System.Type.GetType("System.Int32");
                column.AutoIncrement = true;
                column.AutoIncrementSeed = 1;
                column.AutoIncrementStep = 1;
                dt.Columns.Add(column);
                //

                if (dt.Columns.Contains("TienLuong"))
                {
                    DataColumn column2 = new DataColumn("TienLuongFormat");
                    column2.DataType = System.Type.GetType("System.String");
                    dt.Columns.Add(column2);
                    //
                    dt.Columns.Add("Detail_InsBookNoFormat");

                    //
                    int index = 0;
                    foreach (DataRow row in dt.Rows)
                    {
                        row.SetField(column, ++index);
                        if (row.GetValue<decimal>("TienLuong", 0) < 100)
                            row.SetField("TienLuongFormat", row.GetValue<decimal>("TienLuong", 0).ToString("#,##0.00"));
                        else
                            row.SetField("TienLuongFormat", row.GetValue<decimal>("TienLuong", 0).ToString("#,##0"));

                        //
                        if (row.GetValue<decimal>("Detail_InsBookNo", 0) <= 0)
                            row.SetField("Detail_InsBookNoFormat", "");
                        else
                            row.SetField("Detail_InsBookNoFormat", row["Detail_InsBookNo"]);


                        //Cột ghi chú
                        if (dt.Columns.Contains("Detail_Description"))
                        {
                            string sDescriptions = "";
                            if (row.GetValue<DateTime>("Detail_ToDate", "").ToString("MM/yyyy") == DateTime.Now.ToString("MM/yyyy"))
                            {
                                sDescriptions = row["Detail_InsTypeCode"].ToString() + " đến " + row.GetValue<DateTime>("Detail_ToDate", "").ToString("MM/yyyy")
                                    + (!String.IsNullOrEmpty(row["Detail_Description"].ToString().Trim()) ? (" - " + row["Detail_Description"].ToString()) : "");
                            }
                            else
                                sDescriptions = row["Detail_InsTypeCode"].ToString()
                                    + (!String.IsNullOrEmpty(row["Detail_Description"].ToString().Trim()) ? (" - " + row["Detail_Description"].ToString()) : "");
                            //
                            row.SetField("Detail_Description", sDescriptions);
                        }
                        //
                    }
                }


            }
        }

        private void hồSơTK01ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmToKhaiA01TSOnline frm = new frmToKhaiA01TSOnline();
            frm.ShowDialog();
        }

        private void đăngKýTàiKhoảnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://gddt.bhxhhn.com.vn:8081/register");
            //HRM.Forms._9.NopOnline.frmDangKy frm = new Forms._9.NopOnline.frmDangKy();
            //frm.ShowDialog();
        }

        private void nộpHồSơOnlineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://gddt.bhxhhn.com.vn:8081/ecslevel3/search/#add");

            //HRM.Forms._9.NopOnline.frmNopHS frm = new Forms._9.NopOnline.frmNopHS();
            //frm.ShowDialog();
        }

        private void camKếtTrảThẻToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //
            //Chọn chỗ lưu file xls
            string sFilePath = Util.CreateFolderTemplate();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.doc)|*.doc";
            sfd.InitialDirectory = sFilePath != "" ? sFilePath : Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = "VBCK_10106N_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hhMMssfff") + ".doc";
            if (sfd.ShowDialog(this) == DialogResult.OK)
            {
                sFilePath = sfd.FileName;
                //
                string templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\VBCK_THUHOITHE.doc");
                File.Copy(templateFile, sFilePath);
                Process.Start(sFilePath);
            }
        }

        //GIa hạn thẻ d07b
        private void mẫuD07bToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Chọn chỗ lưu file xls
            string sFilePath = Util.CreateFolderTemplate();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.xls)|*.xls";
            sfd.InitialDirectory = sFilePath != "" ? sFilePath : Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = "D07-TS_30104N_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hhMMssfff") + ".xls";
            if (sfd.ShowDialog(this) == DialogResult.OK)
            {
                sFilePath = sfd.FileName;
                //
                string templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\D07-TS.xls");
                File.Copy(templateFile, sFilePath);
                Process.Start(sFilePath);
            }
        }

        //Gia hạn thẻ - ds in thẻ
        private void dSInThẻToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Chọn chỗ lưu file xls
            string sFilePath = Util.CreateFolderTemplate();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.xls)|*.xls";
            sfd.InitialDirectory = sFilePath != "" ? sFilePath : Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = "PL-D01-TS_30104N_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hhMMssfff") + ".xls";
            if (sfd.ShowDialog(this) == DialogResult.OK)
            {
                sFilePath = sfd.FileName;
                //
                string templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\PL-D01-TS.xls");
                File.Copy(templateFile, sFilePath);
                Process.Start(sFilePath);
            }
        }

        //Gia hạn thẻ - ds in thẻ
        private void dSKhôngTinThẻToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Chọn chỗ lưu file xls
            string sFilePath = Util.CreateFolderTemplate();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.xls)|*.xls";
            sfd.InitialDirectory = sFilePath != "" ? sFilePath : Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = "PL-D01b-TS_30104N_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hhMMssfff") + ".xls";
            if (sfd.ShowDialog(this) == DialogResult.OK)
            {
                sFilePath = sfd.FileName;
                //
                string templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\PL-D01b-TS.xls");
                File.Copy(templateFile, sFilePath);
                Process.Start(sFilePath);
            }
        }

        private void côngVănĐềNghịToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Chọn chỗ lưu file xls
            string sFilePath = Util.CreateFolderTemplate();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.doc)|*.doc";
            sfd.InitialDirectory = sFilePath != "" ? sFilePath : Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = "D01b-TS_30104N_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hhMMssfff") + ".doc";
            if (sfd.ShowDialog(this) == DialogResult.OK)
            {
                sFilePath = sfd.FileName;
                //
                string templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\D01-TS.doc");
                File.Copy(templateFile, sFilePath);
                Process.Start(sFilePath);
            }
        }

        private void d01bCôngVănĐềNghịToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Chọn chỗ lưu file xls
            string sFilePath = Util.CreateFolderTemplate();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.doc)|*.doc";
            sfd.InitialDirectory = sFilePath != "" ? sFilePath : Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = "D01b-TS_10106N_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hhMMssfff") + ".doc";
            if (sfd.ShowDialog(this) == DialogResult.OK)
            {
                sFilePath = sfd.FileName;
                //
                string templateFile = Path.Combine(Application.StartupPath, "ExportTemplate\\D01b-TS_10106N.doc");
                File.Copy(templateFile, sFilePath);
                Process.Start(sFilePath);
            }
        }

        private void dSInThẻToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            dSInThẻToolStripMenuItem_Click(null, null);
        }

        private void cậpNhậtMẫuBiểuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAutoUpdateTemplate frm = new frmAutoUpdateTemplate();
            frm.StartPosition = FormStartPosition.CenterParent;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //if (MessageBox.Show("Phần mềm đã cập nhật bản mới.\nHãy nhấn nút OK để bắt đầu cập nhật hoặc Cancel để cập nhật sau", "HRM", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
                //{
                //    System.Diagnostics.Process.Start(Application.StartupPath + "\\AutoUpdate\\AutoUpdate.exe", "1 " + frm.TemFolder.Trim().Replace(" ", "$$") + " " + frm.FileList);
                //    isFirstLoad = true;
                //    Application.Exit();
                //}
            }
        }

        private void côngVănXinTruyThuTruyGiảmD01bTSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            d01bCôngVănĐềNghịToolStripMenuItem_Click(null, null);
        }

        private void videoHướngDẫnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmWebview frm = new frmWebview();
            frm.Show_Form("http://sis.phuhai.com.vn/video#pm", "Video hướng dẫn");
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            Process.Start(toolStripStatusLabel1.Text);
        }

        private void côngVănToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmWebview frm = new frmWebview();
            frm.Show_Form("http://sis.phuhai.com.vn/congvan#pm", "Mẫu công văn");
        }

        private void hướngDẫnNộpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Process.Start("http://sis.phuhai.com.vn/Media/Default/HuongDan/HD_NopDienTu.doc");
            frmWebview frm = new frmWebview();
            frm.Show_Form("http://sis.phuhai.com.vn/huongdan/noponline#pm", "Hướng dẫn nộp hồ sơ online");
        }
    }
}
